Search code examples
phpoopcallslimmagic-function

slim routing and controller (how this __call function is calling from route and why $this->request is using insted of $request=)


guys please help me to understand these code

in picture 1 router is calling with info method

as you can see in AccountController there is already info() is present then why __call() this magic function is calling

and what are these parameters is $this->request ,$this->response

we can save all data like

$request = $args[0]; $response = $args[1]; $attributes = $args[2];

why $this-> syntex is use what is the meaning of this line $this->$name();

Router.php

<?php

$app->get('/account', '\App\Controller\AccountController:info');

?>

AccountController.php

<?php
/**
 * AccountController
 * @package Controllers
 */
namespace App\Controller;


final class AccountController extends \App\Core\Controller
{

    protected function info()
    {

        echo $this->client_id;

    }
}

Controller.php

 <?php

namespace App\Core;


 class Controller
{


  public function __call($name,$args) { //line 25
        //echo "Call method : ".$name;
        $this->request = $args[0];
        $this->response = $args[1];
        $this->attributes = $args[2];

        //print_r($this->attributes);
        $this->client_id = $this->request->getAttribute("client_id");



              $this->$name();

    }

}


?>

Solution

  • Router.php called your info() method on AccountController.php But your method is protected and info() method not accessible out of the class so __call() magic method has been called with $name and $args parameters.

    $name => value is method name. "info".
    $args => value array of response,request,attributes

    $this => It's a reference to the current object, it's most commonly used in the object-oriented code. What does the variable $this mean in PHP?

    request,response,attributes,client_id they are variables of the controller class and accessible on each method of controller class children. like $this->client_id in your AccountController class.

        $this->request = $args[0];
        $this->response = $args[1];
        $this->attributes = $args[2];
        $this->client_id = $this->request->getAttribute("client_id");
    

    $this->$name(); This dymnaic way for call the methods.

    PHP OOP