duanhuang2804 2016-06-05 04:44
浏览 39
已采纳

在Laravel 5.2中实现合同时出错

I am following this link to implement it

I did below steps to implement the Contract in my existing class.

Below is the class where I will write some logic also before sending it to controller

namespace App\Classes\BusinessLogic\Role;
use App\Classes\DatabaseLayer\Role\RoleDb;
use App\Classes\Contract\Role\IRole;

class RoleBL implements IRole {

    public function All() {
        return (new RoleDb())->All();
    }
}

Database Function

namespace App\Classes\DatabaseLayer\Role; 

class RoleDb {
    public function All() {
        $Roles = \App\Models\Role\RoleModel
                ::all();
        return $Roles;
    }
}

Interface

namespace App\Classes\Contract\Role;

interface IRole {
    public function All();
}

Service Provider class

namespace App\Providers\Role;

class RoleServiceProvider extends \Illuminate\Support\ServiceProvider {

    public function register()
    {
        $this->app->bind('App\Classes\Contract\Role\IRole', function($app){
            return new \App\Classes\BusinessLogic\Role\RoleBL($app['HttpClient']);
        });
    }
}

Finally in config/app.php in provider wrote below line.

App\Providers\Role\RoleServiceProvider::class

Controller - Constructor

protected $roles;
public function __construct(\App\Classes\Contract\Role\IRole $_roles) {
    parent::__construct();
    $roles = $_roles;
}

Controller Action method

public function index(IRole $roles) {
    $RoleTypes = $roles->All();
}

So far everything works fine if I keep Interface as parameter in method.

if I try to use the variable $roles in index method and remove the variable, it is always null.

Please guide me if I missed anything?

  • 写回答

1条回答 默认 最新

  • dongmo8943 2016-06-05 12:26
    关注

    You incorrectly assign the $roles property in your __construct() method.

    Replace

    $roles = $_roles;
    

    with

    $this->roles = $_roles;
    

    and then in your index method do:

    $RoleTypes = $this->roles->All();
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测
  • ¥88 python部署量化回测异常问题