简体   繁体   中英

Laravel controller constructor issue

In some of my controllers, I have common route parameters that are passed for multiple methods. Some of these parameters need some extra processing (string processing) that would require passing the same parameters and calling the same processing methods within each controller method that uses these parameters. Rather than duplicating code, I have a trait included by my controller and the call to that trait in the controller's constructor method.

This works great, I can bind these parameters to the class properties and they can be accessed by all my methods. The problem is when running artisan commands that instantiate controllers, such as artisan route:list . I get the following error when running that command:

Call to a member function getParameter() on null

I know this is because a call to Route::current() will return null since there is no Route or Request object when running artisan, but I find myself having to comment out the code in my trait just to get a list of my routes. I'm sure there are other problems that could arise, too.

My question is, how can I tackle this to be more clean? The only solution I can currently think of is calling my parameter registration method on every controller method, but I'd like to not do that. Any ideas?

Instead of using traits, you can always modify the Controller.php file to include common code that would be inherited by your other controllers. Since all your controllers extends Controller , the common functions would be available so you can just call $this->getParameter() in your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM