Sop*_*des 5 php laravel laravel-5
我目前有一个抽象类,我将其扩展到其他控制器。我在抽象类中有一个抽象函数,它接受值并将它放在__construct.
abstract class Controller extends BaseController {
abstract public function something();
public function __construct(Request $request) {
if (!is_null($this->something())){
$this->global_constructor_usse = $this->something();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,在不需要这个抽象函数的控制器上,我不得不放置在空函数中。
class ControllerExample extends Controller {
public function something(){
return 'somethinghere';
}
}
Run Code Online (Sandbox Code Playgroud)
无论如何使抽象函数可选或具有默认值?
class EmptyControllerExample extends Controller {
public function something(){}
}
Run Code Online (Sandbox Code Playgroud)
或者最好的方法是什么?
父类中的抽象函数仅当您的应用程序需要在继承它的所有控制器中实现以下方法时才应使用,显然事实并非如此。
在这种情况下,我会做一个trait. 在这里您创建一个trait可以由需要它的类实现的。注意use关键字的用法,use somethingTrait;
trait SomethingTrait
{
public function something()
{
echo "something called";
}
}
class Controller
{
use SomethingTrait;
public function run()
{
$this->something();
}
}
Run Code Online (Sandbox Code Playgroud)
class如果要实现方法的控制器有一些共同点,另一种方法可能是创建继承结构。您将在其中实现特殊方法CrmController,您仍然可以methods在抽象控制器中创建共享。
AbstractController
|
CrmController
|
CompanyController
Run Code Online (Sandbox Code Playgroud)
对于你的问题,“是否有办法使抽象函数可选或具有默认值?” 不,如果您试图使抽象函数可选,那么您就走错了路。希望我的建议能够有所帮助。