Laravel study notes (3) Controller

Laravel6 document
Laravel Controller

  1. The default PHP magic methods, __invoke , when the attempt to invoke a function to be called 对象when the method is called automatically

    class invoke
    {
        public function __invoke($x)
        {
            var_dump($x);
        }
    }
     
    $obj = new invoke;
    $obj(10); 
    

    __call and __callStatic , by calling the object's runTest it does not contain a () 方法, the call will automatically __call class () method. When we call this class does not exist 静态方法when runTest (), it will automatically call the class __callStatic () method

    class MethodTest
    {
        public function __call($name, $arguments)
        {
            // 注意:$name的值区分大小写
            echo "Calling object method '$name' " . implode(', ', $arguments) . "\n";
        }
        
        // PHP 5.3.0之后的版本
        public static function __callStatic($name, $arguments) 
        {
            echo "Calling static method '$name' " . implode(', ', $arguments) . "\n";
        }
    }   
    
    $obj = new MethodTest;
    $obj -> runTest('in object context');
    
    // PHP 5.3.0 版本以后
    MethodTest::runTest('in static context');
    

    Laravel, if you want to define only a single process controller behavior, you can place a __invoke method in the controller:

    namespace App\Http\Controllers;
    
    use App\User;
    use App\Http\Controllers\Controller;
    
    class ShowProfile extends Controller
    {
        /**
         * 显示给定用户的资料.
         *
         * @param  int  $id
         * @return View
         */
        public function __invoke($id)
        {
            return view('user.profile', ['user' => User::findOrFail($id)]);
        }
    }
    

    When registering a single routing behavior of the controller, you do not need to specify the method

    Route::get('user/{id}', 'ShowProfile');
    

    You can command in the make tools by Artisan: controller command --invokable option to generate a controller can call:

    php artisan make:controller ShowProfile --invokable
    
  2. In both methods performed only intermediate controller

class UserController extends Controller
{
    /**
     * 实例化一个新的控制器实例.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');

		// 只在方法first和second中执行中间件
        $this->middleware('log')->only('first', 'second');

        $this->middleware('subscribed')->except('store');
    }
}
Published 40 original articles · won praise 0 · Views 790

Guess you like

Origin blog.csdn.net/qj4865/article/details/104093208