To develop a project where I am creating some methods which are common in all the controllers.
Before this I have used codeigniter and there I wrote MY_Controller class in core directory and then I extended the controller in all the controllers in controller directory.
Same I want to do inside Laravel
. But I am confused that where should I write the common methods like send_email
, validate_captcha
, ajax_file_upload
and other common methods which remains same across whole application.
So please suggest me a good way to define such a class or middleware.. What should one do to create that?
OK. Let me suggest some stuffs
App\\Http\\Controllers\\Controller.php
. Because all Controllers in Laravel extend it Step 1 : Write any class you want in app
folder. And follow psr-4
convention
Step 2 : Register to Laravel application In App\\Providers\\AppServiceProvider
. In register()
method. Add
$this->app->bind('bindname', function ($app) {
return new \App\YourClass;
// If you want to inject other class to YourClass contructor
// return new \App\YourClass($app->make('otherbindname'));
});
Step 3 : Use it. There are several ways to access YourClass in your whole application:
app()->make('bindname');
app('bindname');
app()['bindname'];
\App::make('bindname');
//etc
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.