cakephp版本:3.5.17
普普尼特:6.5.8
示例代码:
用户控制器添加操作。(错误代码。)
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
if ($this->clientId() === false) {
}
else {
$clientID = $this->clientId();
}
$user = $this->Users->patchEntity($user, $this->request->getData());
$user->cid_1 = $clientID;
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
客户端ID函数。
public function clientId()
{
$session = $this->request->session();
if ($session->check('Cid.one')) {
$clientID = $session->read('Cid.one');
if (!is_string($clientID) || is_numeric($clientID) || (strlen($clientID) !== 40)) {
return false;
}
return $clientID;
}
return false;
}
过程。
当用户登录时,我选择$clientid并将其存储在会话中,并在应用程序中的许多select语句中使用它。
误差
.
未定义的变量client id-eg:在保存时出错的函数中未检索到客户端id。
总结。
这对我来说很有意义,因为我可以在不登录的情况下运行单元测试,并且在登录时检索客户机id。例:在测试时,客户端ID怎么可能在那里!
我的解决方案。
我不使用会话,而是使用如下所示的查找器。
用户控制器添加操作。(通过的代码。)
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$id = $this->Auth->user('id');
$query = $this->Users->find('cid', [
'id' => $id
]);
if ($query->isEmpty()) {
$errorLocation = 'Users Controller - Line ' . __LINE__;
if ($this->recordError($errorLocation) === false) {
throw new NotFoundException();
}
throw new NotFoundException();
}
$clientID = '';
foreach ($query as $row):
$clientID = $row->cid_1;
endforeach;
$user = $this->Users->patchEntity($user, $this->request->getData());
$user->cid_1 = $clientID;
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
我的问题:
有没有办法模拟测试会话中的$clientid?
我想知道在我的测试中是否有类似的用法:$this->session(['auth.user.id'=>1400]);它模拟
已验证的用户,但用于其他会话数据,如客户端ID?
为什么我问。
这与性能有关。据我所知,从会话中声明值比从数据库中选择值快。
谢谢Z。