Php 从另一个控制器获取服务中定义的变量
我将直截了当地说 我有两个简单的控制器:Php 从另一个控制器获取服务中定义的变量,php,symfony,service,Php,Symfony,Service,我将直截了当地说 我有两个简单的控制器: /** * @Route("/controller1", name="controller1") */ public function controller1(UserVerification $verification) { $verification->setVerificationCode(); return $this->render('user_settings/settings.html.twig'); } /
/**
* @Route("/controller1", name="controller1")
*/
public function controller1(UserVerification $verification)
{
$verification->setVerificationCode();
return $this->render('user_settings/settings.html.twig');
}
/**
* @Route("/controller2", name="controller2")
*/
public function controller2(UserVerification $verification)
{
$verificationCode = $verification->getVerificationCode();
return $this->render('user_settings/settings.html.twig', [
'verificationCode' => $verificationCode
]);
}
我的UserVerification服务中有两种方法:
public function setVerificationCode(){
$this->verificationCode = rand(100000, 999999);
return $this;
}
public function getVerificationCode(): int
{
return $this->verificationCode;
}
我的问题是:在controller1中设置的controller2中获取verificationCode是真的吗?现在,在上面的controller1示例中,当我使用getVerificationCode()方法时,它成功地返回了一些随机代码,但在controller2中,它当然返回null。有没有办法共享服务实例
谢谢你的建议,要点如下:
在Symfony中,默认情况下,服务是共享的,这意味着同一实例正在处理多个请求,如果您想要相反,可以在服务的服务声明中对其进行修改,如:
# config/services.yaml
services:
App\SomeNonSharedService:
shared: false
# ...
但是,这里是不同的,您的函数返回一个随机值,因此即使您使用相同的服务实例,也肯定不会得到相同的结果,所以在这里您可以做两件事:
1-将数据保存到会话中,以防用户登录时出现此逻辑问题:
2-将数据保存到数据库中
对于这两个解决方案,您必须让exmaple验证值是否已经存在于会话/DB中,就像第一个解决方案一样,结果是由您的服务产生的,并且在sametime中将值存储在samewhere中,以便在下一个请求中,它将从您发送数据的位置接收数据
以下是使用会话的示例:
# config/services.yaml
services:
App\Services\CodeService:
arguments:
- "@session"
服务代码:
<?php
namespace App\Services;
use Symfony\Component\HttpFoundation\Session\Session;
class CodeService
{
private $session;
public function __construct( Session $session)
{
$this->session = $session;
}
pulic function setVerificationId(){
if(isset(!$this->session->get('verificationCode'))){
$this->session->set('verificationCode', rand(100000, 999999));
}
return this->getVerificationId();
}
public function getVerificationId()
{
return $this->session->get('verificationCode');
}
}
您对这些控制器有两个单独的请求。您应该将数据保存在数据库、会话或其他地方。@MagnusEriksson如果没有其他定义-symfony容器将返回相同的服务实例。所以,我假设OP只使用了两个请求,并且希望它们之间的数据能够以某种方式保存。如果你想在两个请求之间共享数据,你必须像@u_mulder所说的那样将数据保存在某个地方。你使用的是什么symfony版本?我使用的是symfony 4在会话中存储数据是安全的?我的意思是,在我的例子中,代码不应该被未经授权的人获取,所以如果你想将数据存储到数据库中,你可以用同样的方法来实现,只需插入会话,使用EntityManager