更新时间:2023-02-01 10:14:41
如果您希望将范围之外的会话注入您的自定义扩展.
If you are looking to inject sessions outside of the scope meaning into your custom extension.
我会这样做.
//AppKernel +add
protected function initializeContainer() {
parent::initializeContainer();
if (PHP_SAPI == 'cli') {
$this->getContainer()->enterScope('request');
$this->getContainer()->set('request', new \Symfony\Component\HttpFoundation\Request(), 'request');
}
}
然后在您的服务容器中
<!-- Custom Twig Extensions -->
<service id="yourid" class="yourclasspath">
<argument type="service" id="service_container" />
<tag name="twig.extension" />
</service>
然后在你的 twig.php
Then in your twig.php
class Twig extends \Twig_extension {
private $request;
public function __construct(Container $container) {
$this->request = $container->get('request');
}
public function getFunctions() {
return array(
'count' => new \Twig_Function_Method($this, 'count'),
);
}
public function count() {
$session = $this->request->getSession();
if(session->has('count')) {
$session->set('count') += 1;
} else {
$session->set('count') = 1;
}
return $session->get('count');
}
}
然后在你的树枝上也一样
Then the same in your twig