Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/228.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel扩展了雄辩的第三方课程_Php_Laravel_Eloquent - Fatal编程技术网

Php Laravel扩展了雄辩的第三方课程

Php Laravel扩展了雄辩的第三方课程,php,laravel,eloquent,Php,Laravel,Eloquent,我目前正在进行我的第一个PHP/Laravel4项目,我正在开发一个存储类,为第三方库添加有力的支持 我的EloquentStorage类扩展了库中的AbstractStorage类,并且我使用了大多数AbstractStorage方法。现在我想为我的新EloquentStorage类添加Eloquent支持,我面临的事实是PHP不支持多重继承 有没有合适的方法来定义雄辩的模型,而不将其扩展为: class MyClass extends Eloquent {} 如果没有,当我需要扩展第三方课

我目前正在进行我的第一个PHP/Laravel4项目,我正在开发一个存储类,为第三方库添加有力的支持

我的EloquentStorage类扩展了库中的AbstractStorage类,并且我使用了大多数AbstractStorage方法。现在我想为我的新EloquentStorage类添加Eloquent支持,我面临的事实是PHP不支持多重继承

有没有合适的方法来定义雄辩的模型,而不将其扩展为:

class MyClass extends Eloquent {}

如果没有,当我需要扩展第三方课程和扩展口才时,如何处理这种情况?也许使用拉威尔的IoC?

我认为您的模型应该从
雄辩的
扩展,而是通过。您的存储库可以有一个
$storage
属性,并负责在
AbstractStorage
实现上调用适当的方法。下面是更多的伪代码,而不是实际代码,但说明了可以在何处插入实现以进行更新操作

class MyClass extends Eloquent 
{
    /* Normal Eloquent model implementation */
}

class MyRepository
{
    protected $storage;
    protected $myClass;

    public function __construct(MyClass $myClass, AbstractStorage $storage)
    {
        $this->myClass = $myClass;
        $this->storage = $storage;
    }

    public function update($id, $data)
    {
        // This is just an example operation, basically here's your chance to call 
        // the 3rd-party implementation. Here is pre-eloquent update, but can be 
        // after
        $this->storage->update($id, $data);

        // Use the empty Eloquent class property instance to obtain an instance of 
        // the requested model
        $instance = $this->myClass->find($id);
        // set instance properties
        $instance->save();

        // Example post-eloquent update
        $this->storage->update($id, $data);
    }
}

class MyStorage extends AbstractStorage { /* Your Storage Implementation */ }

$repo = new MyRepository(new MyClass, new MyStorage);
// Update item id 42's foo property
$repo->update(42, [ 'foo' => 'bar' ]);
这种方法的一个好处是,存储库本身的构造可以通过服务提供商卸载给IoC,并注入控制器/表单验证器等内部,这意味着执行将自动进行,并对系统的其余部分隐藏第三方库的潜在复杂性(存储库有助于保持您的第三方抽象)

另一个好处是,在雄辩的模型中,您不需要任何与完全无关的第三方代码相关的特殊代码。所有逻辑都封装在一个点中,甚至可以在多个模型之间共享。要更改第三方提供程序吗?编写一个新的
AbstractStorage
实现,最多和服务提供商约会,你就完成了


另一个好处是提高了可测试性。与直接静态地使用雄辩的模型(la
$user=user::find($id)
)不同,您将操作您的存储库对象(
$user=$this->repo->find($id)
)。因为您的存储库可以被简单地模拟并进行测试(无需测试Elount或访问数据库),您就可以在所有控制器路由上编写集成测试,并知道对代码库的更改何时会违反您的业务规则。

这是一种很棒的方法,我们现在就尝试一下,并返回结果。谢谢@Watcher