英文:
Laravel 2 construct in trait collide
问题
You can resolve the collision issue between the two trait constructors by explicitly calling both constructors within your controller's constructor using the parent::__construct()
method. Here's the modified code:
namespace App\Http\Controllers;
// ...
use App\Traits\TraitOne;
use App\Traits\TraitTwo;
class UserAuthController extends Controller
{
use TraitOne, TraitTwo;
public function __construct()
{
// Call the constructors of both traits
parent::__construct();
TraitOne::__construct();
TraitTwo::__construct();
}
public function createUser(Request $request)
{
// calling trait one methods
$checkUser = $this->createLead($request);
// calling trait two methods
$checkUser = $this->getUser($request->email);
}
}
By explicitly calling the constructors of both traits in your controller's constructor, you can use both traits simultaneously without encountering the collision issue.
英文:
I'm using 2 trait, each trait has it own construct method, but when 2 trait is import in same controller, the construct method create collisions.
Trait one
`<?php
namespace App\Traits;
...
trait TraitOne
{
private $apiUrl;
...
public function __construct()
{
...
}`
Trait two
`<?php
namespace App\Traits;
...
trait TraitTwo
{
public $NEW_PASSWORD_CHALLENGE = 'NEW_PASSWORD_REQUIRED';
...
private $key;
...
public function __construct()
{
...
}`
Controller
`<?php
namespace App\Http\Controllers;
...
use App\Traits\TraitOne;
use App\Traits\TraitTwo;
...
class UserAuthController extends Controller
{
use TraitOne, TraitTwo;
public function createUser(Request $request)
{
// calling trait one methods
$checkUser = $this->createLead($request);
// calling trait two methods
$checkUser = $this->getUser($request->email);
}
}`
I'm having error like
Trait method __construct has not been applied, because there are collisions with other trait methods on App\Http\Controllers\UserAuthController
Both construct method is important, how can I use 2 trait at the same time?
I have no idea what should I do next.
答案1
得分: 1
你可以给特质构造方法取别名:
导入其中一个特质(考虑将TraitOne
别名为 as
)。
use TraitOne{
TraitOne::__construct as constructorOne
};
现在你可以在你的构造函数中轻松使用它:
$this->constructorOne();
更多信息请查看这里:https://www.php.net/manual/en/language.oop5.traits.php
英文:
You could alias the trait constructor methods:
Import either one of the trait as(Considering the TraitOne
to be aliased).
use TraitOne{
TraitOne::__construct as constructorOne
};
Now you could easily use it within your constructor as:
$this->constructorOne();
More info here: https://www.php.net/manual/en/language.oop5.traits.php
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论