编辑父变量

时间:2017-03-16 22:24:28

标签: php laravel oop laravel-5.2

所以我试图从子类中编辑属性category,但由于某些原因我得到了错误。我知道为什么因为需要有2个参数,但是已经在de parent class中设置了一个参数。

代码:

孩子

class RestaurantController extends CompanyController
{
    public function __construct(){
        parent::__construct(null, "restaurant");
        //$this->category = "restaurant";
    }
    public function getCompany($slug){
        $company = parent::index($slug);
        return view("restaurant.profile")->withInformation($company);
    }
} 

父母

class CompanyController extends Controller 
{
    protected $company;
    public $category;

    public function __construct(CompanyRepository $company, $category = '')
    {
        $this->category = $category;
        $this->company = $company;
    }

    public function index($slug)
    {
        $company = $this->company->getCompany($this->category, $slug);

        return compact('company');
    }
}

现在我需要知道如何解决这个问题。

EDIT1

我得到的错误

类型错误:传递给App \ Http \ Controllers \ CompanyController :: __ construct()的参数1必须是App \ Repositories \ CompanyRepository的实例,给定null,在/var/www/atify.info/dev-system中调用第16行的/app/Http/Controllers/RestaurantController.php

EDIT2

这个孩子

class RestaurantController extends CompanyController
{
    public function getCompany($slug){
        $company = parent::index($slug);
        return view("restaurant.profile")->withInformation($company);
    }
} 

父母

use App\Repositories\CompanyRepository;
class CompanyController extends Controller 
{
    protected $company;

    public function __construct(CompanyRepository $company)
    {
        $this->company = $company;
    }

    public function index($slug)
    {
        $company = $this->company->getCompany($slug);

        return compact('company');
    }
}

那么我需要一个类别(额外检查。否则你可以在另一个有错误功能的孩子里找回公司),因为我有很多孩子,每个孩子都有特殊的功能

1 个答案:

答案 0 :(得分:0)

我认为这是你想要的儿童班:

class RestaurantController extends CompanyController
{
    public $category = 'restuarant';

    public function __construct(CompanyRepository $company){
        parent::__construct($company, $this->category);
    }

    public function getCompany($slug){
        $company = parent::index($slug);
        return view("restaurant.profile")->withInformation($company);
    }
} 

如果您正在构造函数中执行此操作,则可以消除子构造函数并更改父构造函数。

 public function __construct(CompanyRepository $company, $category = null)
    {
      if( $category ){
        $this->category = $category;
      }
      $this->company = $company;
    }

然后每个子类只设置类别属性

class ChildController extends CompanyController
{
    public $category = 'Child';
}