如何在 CakePHP 2.4 中的多个控制器操作中重用样板查询代码?
我有一些连接代码需要在多个操作中重复使用,这不包括属于Project.published = 0
从我的find()
中项目的所有帖子。我通过创建一个公共类数组来保存查询代码来完成此操作。
这有效,但是我想根据变量添加一些额外的参数 - 特别是允许Project
的所有者查看属于其项目的数据,即使它未发布。
如果阵列作为控制器操作的一部分集成,我只需将'ProjectAlias.user_id' => CakeSession::read("Auth.User.id")
添加到下面的最终OR
数组中。但是,我不能将其作为类数组的一部分包含在内,我需要在操作中创建它,如下所示。
这感觉不是特别优雅。有没有更清洁/更蛋糕的方式来解决这个问题?
我当前的代码:
//==============
// ADDITIONAL JOIN TO RESTRICT RESULTS TO LIVE PROJECTS
//================
public $joins = array(
array(
'table' => 'projects',
'alias' => 'ProjectAlias',
'type' => 'right',
'conditions' => array(
'OR' => array( // One of these two things:
'Post.project_id' => null, // Posts with no project
'AND' => array( // And posts with a Project that is published.
'Post.project_id = ProjectAlias.id',
'OR' => array(
'ProjectAlias.published !=' => 0,
)
)
)
),
)
);
//===============
// Example function showing how this array is used. There are four in all
// so repeating the above code would get to be too much.
//================
public function example() {
// Let project leads see data from their hidden projects, by modifying the array.
// This doesn't seem very elegant!
$this->joins[0]['conditions']['OR']['AND']['OR'][] = array(
'ProjectAlias.user_id' => CakeSession::read("Auth.User.id")
);
// Use the array
$this->paginator->settings['joins'] = $joins;
$this->set('posts', $this->Paginator->paginate());
}
如果我理解正确,你可以创建一个函数,该函数需要在 AppController 中调用参数,该函数返回连接数组并从任何控制器的任何操作中调用它。现在,关于不同情况下的不同参数,首先您可以使用-
$this->request->action
获取当前操作(如果需要,也可以获取控制器)。现在,您可以在 AppController 的函数中设置关联数组或 else 块,以根据需要使用函数参数来定义连接数组。然后,您可以从任何操作中获取定制的$joins数组。