如何在所有操作中默认调用控制器的init()方法

时间:2017-08-06 12:56:55

标签: php zend-framework3

class IndexController extend AbstractActionController
{
    construct__()
    {
        $view = new ViewModel();
    }

    public function init()
    {
        $exp = 'exemple';
        $this->view->setVariable('exp', $exp);
    }

    public function indexAction()
    {
        // I Want call init in all action without $this->init();
    }

    public function aboutAction()
    {
        // I Want call init in all action without $this->init();
    }
}

默认情况下,我希望在此控制器的所有操作上调用函数init(),而无需手动输入$this->init()

2 个答案:

答案 0 :(得分:0)

假设您的路线定义如下(module.config.php):

<?php

namespace Application;

use Zend\Router\Http\Literal;

return [
    // …
    'router' => [
        'routes' => [
            'about' => [
                'options' => [
                    'defaults' => [
                        'action'     => 'about',
                        'controller' => Controller\IndexController::class
                    ],
                    'route' => '/about'
                ],
                'type' => Literal::class
            ],
            'home' => [
                'options' => [
                    'defaults' => [
                        'action'     => 'index',
                        'controller' => Controller\IndexController::class
                    ],
                    'route' => '/'
                ],
                'type' => Literal::class
            ]
        ]
    ]
    // …
];

正如您所看到的,abouthome路由指向不同的操作,而您希望它们执行相同的操作,即调用IndexController::init()方法。但是你可以简单地让两个路由指向同一个动作,结果,在一个方法中做同样的事情而不是调用IndexController::init()

让我们简化您的IndexController - 删除所有方法并添加一个commonAction

<?php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    public function commonAction()
    {
        // perhaps do other things
        return new ViewModel(['exp' => 'exemple']);
    }
}

现在,您可以返回module.config.php并指示路由器对commonActionabout路由使用home。只需更换两个

'action' => 'about'

'action' => 'index'

'action' => 'common'

答案 1 :(得分:0)

// I find solution in my question 
//thanks for all peopole that they help me 

class indexController extends AbstractController{

public function __construct()
{
$this->init();
}

protected function init()
{
$view = new ViewModel();
$view->setVariaa*ble($tt,'message')

return $view;
}

public function indexAction()
{
return $view;
}