通常,您会编写一个方法来代理您需要的任何值,然后调用该方法,调用$this->getEntity()
它只比调用贵一点$this->entity
,据我所知,这是既定目标
class RestController
{
protected $entity;
public function getEntity()
{
if (!$this->entity) {
$this->entity = $this->params()->fromRoute('entity');
}
return $this->entity;
}
}
如果您确实想预先填充实体属性,最简单的方法是使用初始化程序,并将代码从您的__construct
or 移动到init()
. 让你的控制器实现\Zend\Stdlib\InitializableInterface
use Zend\Stdlib\InitializableInterface;
class RestController extends AbstractRestfulController implements InitializableInterface
{
protected $entity;
public function init() {
$this->entity = $this->params()->fromRoute('entity');
}
}
在你的模块 boostrap 中添加一个初始化器到控制器加载器
use Zend\Stdlib\InitializableInterface;
class Module
{
public function onBootstrap(MvcEvent $e)
$sm = $e->getApplication()->getServiceManager();
$controllers = $sm->get('ControllerLoader');
$controllers->addInitializer(function($controller, $cl) {
if ($controller instanceof InitializableInterface) {
$controller->init();
}
}, false); // false tells the loader to run this initializer after all others
}
}