Cakephp 需要模型中的会话变量

Cakephp need session var in model

我给。几个小时以来一直在搜索和尝试不同的东西。 使用 Cakephp 2.3.5.

我会直截了当。 我想在我的类别模型中使用会话变量,但当我尝试以下任何操作时它不喜欢它...

$this->Session->read('market_id')
CakeSession::read('market_id')
SessionHelper::read('market_id')

这是我尝试使用它的模型片段...

public $hasAndBelongsToMany = array(
    'Vendor' => array(
        'className' => 'Vendor',
        'joinTable' => 'categories_vendors',
        'foreignKey' => 'category_id',
        'associationForeignKey' => 'vendor_id',
        'unique' => 'keepExisting',
        'conditions' => array( 'market_id' => ???? ) 
    )
);

我像手推车一样陷在泥里。我已经阅读了无数关于为什么我不应该在模型中使用会话数据的意见,但这对我来说非常有意义,因为如果没有这个值集就永远不会调用它,并且它永远不会 return 除了market_id 的供应商。但是这个值确实改变了。

我对尽我所能避免弄乱我的模型感到非常内疚。整个瘦控制器的想法……是的……不错的想法,但我还没有弄清楚。事情就是这样。第一次尝试修改模型...我不知道怎么做。

I've read countless opinions of why I shouldn't use session data in the model

没错。它也会导致紧密耦合并使其更难测试。它不仅对模型有效,而且对所有事物都有效。不要创建紧密耦合的代码。

最好传递数据和对象。例如:

// Model Method
public function getSomething($someSessionValue) { /*...*/ }
// Controller
$this->SomeModel->getSomething($this->Session->read('something'));

如果您需要很多方法的数据,您可以设置它:

public function setSomeModelProperty($value) {
    $this->_someProperty = value; // _ because it should be protected, the _ is the convention for that in CakePHP
}

但是,我个人非常喜欢将数据传递给每个方法。不过要看整个场景。

And you can't do this any way because it will cause a syntax error. 不能在 属性 声明中使用变量或属性。

'conditions' => array( 'market_id' => ???? ) 

所以 bind it later 通过类似

的方法
public function bindVendors($marketId) {
    $this->bindModel(/*...*/);
}

需要时。

或者更好的是,仅在需要时使用条件并在查找选项中声明它们:

[
    'contain' => [
        'Vendor' => [
            'conditions' => /* conditions here */
        ]
    ]
]