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

How to call init() method of a controller by default in all actions

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()

假设您的路由定义如下 (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 并指示路由器对 abouthome 路由使用 commonAction。只需替换两者

'action' => 'about'

'action' => 'index'

'action' => 'common'

// 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;
}