Functions inside controller

In controller(eg. work.php), i want to call a function or a variableinside default controller is like

$x = 'nothing works';
function do_work(){
   return $x;
}
return function () {
    return do_work();
}

How can this be achieved? I am new to Kirby, i would require a in depth explanation to understand it. Thank You in advance.

There are some issues with your code.

  1. The function itself will not work, because $x is not defined inside the do_work() function. Head over to php.net to learn more about variable scopes. This is general PHP knowledge, not Kirby specific.
  2. You would have to define your function inside the controller function (or in a plugin).
  3. Your controller has to return an array, not a simple string, so even if that function was correctly defined inside the controller and would work, the controller wouldn’t work, see the docs: https://getkirby.com/docs/guide/templates/controllers#creating-a-controller

This would work and return the variables $a and $b to the template:

return function () {
  $x = ['a' => 'a', 'b' => 'b'];
  
  function do_work($x){
    return $x;
  }
    return do_work($x);
}

It usually makes more sense to define functions in a plugin, unless you really only need it once inside the controller.

1 Like

i was eagerly waiting since you were typing. Variable declared in a file used to have a scope like javascript like it can be used by any function or may be i got confused. i really didn’t new function inside a function is possible. i thought it was only available in python or javascripts. But i would be pleased if the above code works. I took all your directions very seriously.
I was tracking your code to write methods at link and wondering how thing guy is doing what he is doing and where exactly is this file or what is this file …its not like a controller and if i declare methods like this, can i use it under $page? so i even tried to change the methods to that gist format but seems like the page:: was missing. This is what happens when you don’t understand the internal structure. But seeing you typing here with such a low response time was amazing. I am flattened. Thanks and TC

Oh, the code from my gist refers to Kirby 2, not the current Kirby 3 version. Please don’t use that.

1 Like

If you provide more information what exactly you want to achieve, we can help you better.

1 Like

Thank you for asking it. I apologize for my scary coding it might disappoint you … but below is the code.

<?php

use Kirby\Http\Remote;
use Kirby\Cms\Pagination;

return function ($page) {
	$validate = [
				'investment_center' => [
					'required' => [
						'from_date',
						'to_date',
						'page_no',
						'start'
					],
					'not_required' => [

					]
				]
			];
			
	$err_code = [
	 	'Invalid Parameters Passed'
	];

	function prnt($data, $exit=0, $type='print_r'){
        print "<pre>";
        print_r($data);
        print "</pre>";
    
        if($exit){
            exit;
        }
    }
    
    function validate($type = 'investment_center'){
        /**
         * desc:
         *      This will validate and return objets of all values parsed
         *      else will return false 
         */
        foreach($validate[$type] as $key => $param){
            if($key == 'required'){
                foreach($validate[$type][$key] as $param){
                    if (!empty($_REQUEST[$param])){
                        $params[$param] = $param;
                    }
                    else{
                        return false;
                    }
                }
            }
    
            if($key == 'not_required'){
                foreach($validate[$type][$key] as $param){
                    if (!empty($_REQUEST[$param])){
                        $params[$param] = $param;
                    }
                }
            }
    
            return $params;
        }
    }
    
    function get_to_from_date()
    {
        /**
         * return:
         *      $params['from_date'=>'dd-mm-yyyy', 'to_date' => 'dd-mm-yyyy']
         */
        if (!empty($_REQUEST['from_date']) && !empty($_REQUEST['to_date'])) {
            $from_date = date('d-M-Y', strtotime(str_replace('/', '-', $_REQUEST['from_date'])));
            $to_date =  date('d-M-Y', strtotime(str_replace('/', '-', $_REQUEST['to_date'])));
    
            $params['from_date'] = $from_date;
    
            $params['to_date'] = $to_date;
    
            return $params;
        }
        return false;
    }
    
	function get_data_from_api($url, $params, $type='GET')
	{
        try {
            // print_r($params);
            $response = Remote::get(
                                    $url, 
                                    array(
                                        'data' => $params
                                    )
                                );
            return $response;
            //         print_r($request);
            // exit;       
        } catch (\Exception $e) {
            $error = 'Could not fetch the details from api';
        }
    }
    
    function investment_center($raw_params, $page_limit=20)
    {
        $url = 'http://services.xyz.com/cw/ter';
        $params['from_date'] = $raw_params['from_date'];
        $params['to_date'] = $raw_params['to_date'];
        $params['limit'] = $page_limit;
        $params['start'] = $raw_params['start'];
        $page_no = $raw_params['page_no'];
    
        $response = get_data_from_api($url,$params);
    
        if (!empty($response) && !empty($response->content)) {
    
            $result['content'] = $response->json(false)->list;
    
            $total = count($result['content']);
            
            // prnt($result['content']);
            // print "<pre>";
            // print_r($request->json(false)->count);
            // print "</pre>";
        }
    
        return [
            'country' => 'India',
            'result' => $result,
            'total' => $total,
            'error' => $error,
            'from_date' => $params['from_date'],
            'to_date' => $params['to_date'],
            'page_limit' => $page_limit,
            'start' => $params['start']
        ];
    
    }


	try{
		if (!empty($_REQUEST)) {
			if (!empty($_REQUEST['type'])) {
				$type = $_REQUEST['type'];
				switch ($type) {
					case 'investment_center':
						$params = validate('investment_center');
						prnt($result['content'], 1);
						return $params ? invsetment_center($params) : false;
						break;

					default:
						throw new Exception($err_code[0]);
				}
			} else {
				throw new Exception($err_code[0]);
			}
		} else {
			throw new Exception($err_code[0]);
		}
	}
	catch (\Exception $e) {
        echo 'Message: ' .$e->getMessage();
    }
}

?>

i am getting exception message as “Message: Undefined variable: validate”

That’s because of this line, the variable is defined outside of the function and not passed to it. As I already said above, mind your variable scope. We cannot possibly debug all your code for you… This has nothing to do with Kirby in particular.

Okie true

yup, no i will do it. Thank You.