Laravel 里面model如何重用
伊谢尔伦
伊谢尔伦 2017-05-16 16:53:44
[PHP讨论组]

我们公司现在在用Laravel开发项目,同时还增加了Biz层和Repositories层,来实现业务逻辑封装,反而model里面什么代码都没有。
Controller里写代码的时候,尝尝困扰我的问题是如果复用Biz对象,Repositories对象和Model对象。
以前用Yii开发项目的时候,有一个工厂模式,所以调用Model的时候,基本都不new,都是字节用 XXX::model() 来调用的,一个对象被new一次就够了,能有效节省内存。
Controller代码:

$productModel = Product::model()->getList('xxxxxxxxx');

多简单,有没有?

Laravel里,Model好像没有工厂,要调用,都需要实例,假如Repositories里面封装了5个方法,每个都使用了Model,那么我在Controller里调用了这5个方法,Model就被new了5次。
目前在网上看到一种办法,就是在Repositories的构造函数里注入Model对象,放在Repositories的私有成员变量里,这样5个方法都调用当前类的私有变量就可以了。但使用起来就麻烦了,在Controller里写代码的时候,需要这样写:

$xxxBiz = new XXXBiz(\xxx\xxx\Repositories);

在Repositories里需要这样写:

$xxxRepositories = new XXXRepositories(\xxx\xx\xxxModel);

在new一个Biz的时候,还必须传入Repositories对象,而且命名空间还老长,我基本都是在拼字符串了,写代码效率超低,还要打开这写文件,去把名字拼出来。

想问一下大家在用Laravel开发项目的时候,是如何解决Model这种逻辑层类复用的情况?

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

全部回复(2)
PHP中文网

我司是继承一个BaseRepository,BaseRepository中定义

protected function getUserCouponModel($new = false)
{
    if (is_null($this->userCouponModel) || true === $new) {
        $this->userCouponModel = new UserCouponModel();
    }
    return $this->userCouponModel;
}

CouponRepository中

public function create($couponID)
{
    $attributes = [
        'couponID' => $couponID,
    ];

    return $this->getUserCouponModel(true)->create($attributes);
}

Biz中类似,继承一个BaseBiz,然后方法这么写

public function create($fields)
{
    return $this->getCouponRepository()->create($fields);
}

Controller中调用

$biz = new Biz();
$biz->create($fields);

Controller ---> Biz ---> Repository

淡淡烟草味

我是这么做的,在底层 model 里建立这个函数
修改bootstrap/app.php 和 AppServiceProvider.php
具体参考 Service Provider

    static public function load(){
        return app()->make(get_called_class());
    }

在controller 里调用 Foo::load() 就可以了

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号