在我的自定义类中注入 Silex $app [英] Inject Silex $app in my custom class
问题描述
我在参与 Silex 项目,我使用类进行不同的处理:
I'm on a Silex project and I use classes to different treatments:
$connection = new Connection($app);
$app->match('/connection', function () use ($app, $connection) {
$connexion->connectMember();
return $app->redirect($app['url_generator']->generate('goHome'));
})->method('GET|POST')->bind('doConnection');
在我的类Connection"的函数connectMember()"中,我有:
In the function 'connectMember()' of my class 'Connection', I have :
[...]
if($isMember){
[...]
}else{
return $this->_app['twig']->render(
'message.twig',
array('msg' => "This member does not exist.", 'class' => 'Warning'));
}
[...]
但是render()方法不起作用.我想显示的错误消息没有显示,而是启动了$ app->redirect (...)".
But the render () method is not working. The error message I want to display is not displayed and "$ app-> redirect (...)" is launched instead.
如何让我的班级使用当前对象 Silex\Application ?是否有更好的方法将自定义类绑定到 Silex 应用程序的实例?
How to make my class uses the current object Silex\Application ? Is there a better method to bind a custom class to the instance of the Silex application?
非常感谢您的回答!
版本:添加信息
如果我使用:
return $connexion->connectMember();
显示错误消息.但这不是一个好的解决方案.连接"类调用其他也使用此代码的类:
The error message is displayed. But it's not a good solution. The 'connection' class calls other classes that also use this code:
$this->_app['twig']->render(...).
如何使 $this->_app(存在于我的类中)对应于我在控制器中创建的变量 $app?
How to make $ this->_app (present in my classes) correspond to the variable $app created in my controller?
推荐答案
为Connection
(或Connexion
??)类创建一个服务并注入应用程序:
Create a service for the Connection
(or Connexion
??) class and inject the application:
use Silex\Application;
class Connection
{
private $_app;
public function __construct(Application $app)
{
$this->_app = $app;
}
// ...
}
$app['connection'] = function () use ($app) {
return new Connection($app); // inject the app on initialization
};
$app->match('/connection', function () use ($app) {
// $app['connection'] executes the closure which creates a Connection instance (which is returned)
return $app['connection']->connectMember();
// seems useless now?
return $app->redirect($app['url_generator']->generate('goHome'));
})->method('GET|POST')->bind('doConnection');
在 silex 和 pimple(pimple 是 silex 使用的容器).
Read more about it in the documentation of silex and pimple (pimple is the container used by silex).
这篇关于在我的自定义类中注入 Silex $app的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!