2017-03-16 62 views
-1

所以我試圖從子類編輯屬性category,但由於某些原因,我收到一個錯誤。這我知道爲什麼,因爲需要有2個參數,但其中一個是在父類中設置的。編輯父變量

代碼:

的兒童

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

我得到的錯誤

類型錯誤:傳遞給應用程序參數1 \ HTTP \ \控制器:: CompanyController結構__()必須應用\庫\實例CompanyRepository ,空給出稱爲/var/www/atify.info/dev-system/app/Http/Controllers/RestaurantController.php第16行

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'); 
    } 
} 

於是我需要一個類別(額外的檢查。否則,你可以檢索與錯功能的另一個子裏面的公司),因爲我有很多孩子的每個孩子都有特殊的功能

+0

請包括你得到錯誤。 – jfadich

+0

@jfadich編輯! – DevJoeri

+0

您將'null'作爲第一個參數傳遞給'parent :: __ construct(null,「restaurant」);'但父方法要求您傳遞'CompanyRepository'對象作爲第一個參數....您需要一個'CompanyRepository'對象來通過,而不是那個null –

回答

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'; 
} 
+0

那麼工作!但是現在每次我調用擴展'CompanyController'時,我必須在構造函數中添加它? – DevJoeri

+0

不是,你可以設置類別並在父構造器中處理它(我會更新答案) – dan08