Bluz\Controller\Controller::run PHP Method

run() public method

__invoke
public run ( array $params = [] ) : Data
$params array
return Data
    public function run($params = [])
    {
        // initial variables for use inside controller
        $module = $this->module;
        $controller = $this->controller;
        $cacheKey = 'data:' . $module . ':' . $controller . ':' . http_build_query($params);
        if ($this->getReflection()->getCache()) {
            if ($cached = Cache::get($cacheKey)) {
                return $cached;
            }
        }
        $data = $this->getData();
        /**
         * @var \closure $controllerClosure
         */
        $controllerClosure = (include $this->getFile());
        if (!is_callable($controllerClosure)) {
            throw new ControllerException("Controller is not callable '{$module}/{$controller}'");
        }
        // process params
        $params = $this->getReflection()->params($params);
        // call Closure or Controller
        $result = $controllerClosure(...$params);
        // switch statement for result of Closure run
        switch (true) {
            case $result === false:
                // return "false" is equal to disable view and layout
                $this->disableLayout();
                $this->disableView();
                break;
            case is_string($result):
                // return string variable is equal to change view template
                $this->template = $result;
                break;
            case is_array($result):
                // return associative array is equal to setup view data
                $this->getData()->setFromArray($result);
                break;
            case $result instanceof Controller:
                $this->getData()->setFromArray($result->getData()->toArray());
                break;
        }
        if ($this->getReflection()->getCache()) {
            Cache::set($cacheKey, $this->getData(), $this->getReflection()->getCache());
            Cache::addTag($cacheKey, $module);
            Cache::addTag($cacheKey, 'data');
            Cache::addTag($cacheKey, 'data:' . $module . ':' . $controller);
        }
        return $this->getData();
    }

Usage Example

Example #1
0
 /**
  * Do dispatch
  *
  * @param  string $module
  * @param  string $controller
  * @param  array  $params
  * @return Controller
  */
 protected function doDispatch($module, $controller, $params = [])
 {
     // @TODO: try to find custom controller class
     // create controller controller
     $controllerInstance = new Controller($module, $controller);
     // check HTTP Accept header
     $controllerInstance->checkAccept();
     // check HTTP method
     $controllerInstance->checkMethod();
     // check ACL privileges
     $controllerInstance->checkPrivilege();
     // run controller
     $controllerInstance->run($params);
     return $controllerInstance;
 }