每当我向Eloquent 的模型添加额外的逻辑时,我最终不得不将其设置为static
个方法(即不太理想),以便从模型的外观调用它.我已经try 了很多关于如何以正确的方式实现这一点的搜索,几乎所有的结果都讨论了如何创建返回部分查询生成器界面的方法.我试图找出如何添加可以返回任何内容并使用模型的facade调用的方法.
For example, lets say I have a model called Car
and want to get them all:
$cars = Car::all();
很好,除了现在,假设我想通过make将结果排序为多维数组,这样我的结果可能如下所示:
$cars = array(
'Ford' => array(
'F-150' => '...',
'Escape' => '...',
),
'Honda' => array(
'Accord' => '...',
'Civic' => '...',
),
);
以这个理论为例,我很想创建一个方法,可以像这样调用:
$cars = Car::getAllSortedByMake();
让我们暂时忘记这个可怕的方法名,以及它与数据 struct 紧密耦合的事实.如果我在模型中使用这样的方法:
public function getAllSortedByMake()
{
// Process and return resulting array
return array('...');
}
And finally call it in my controller, I will get this Exception thrown:
假设$this来自不兼容的上下文,则不应静态调用非静态方法Car::getAllSortedByMake()
TL;DR:我如何添加在模型中有意义的自定义功能,而不使其成为静态方法,并使用模型的facade调用它?
编辑:
This is a theoretical example. Perhaps a rephrase of the question would make more sense. Why are certain non-static methods such as all()
or which()
available on the facade of an Eloquent model, but not additional methods added into the model? This means that the __call
magic method is being used, but how can I make it recognize my own functions in the model?
可能比"排序"更好的示例是,如果我需要对一段数据运行计算或算法:
$validSPG = Chemical::isValidSpecificGravity(-1.43);
对我来说,这样的东西出现在模型中是有意义的,因为它是特定于领域的.