The request
class is used to capture all incoming request parameters and headers.
Controllers can be injected with class based parameters, which the framework will initialize and later on pass on to the controller methods. To inject the request
class, simply create the Request
parameter as such:
namespace Application\Controllers;​use Application\Controllers\Controller;use MightyCore\Http\Request;​class FooController extends Controller{public function bar(Request $request){// Here $request will be initialized and ready to be accessed.}}
By doing so, we are able to the get the query parameters of the request:
class FooController extends Controller{// Redirecting to method based on www.example.com?foo=HelloWorldpublic function bar(Request $request){$foo = $request->query("foo");echo $foo; // HelloWorld}}
In order to acquire the header(s) of the request, simply use the header()
method.
class FooController extends Controller{public function bar(Request $request){$authorization = $request->header("Authorization");$allHeaders = $request->header();}}
If header()
method does not have a parameter, it will simply return all request headers in an array.
In order to obtain the files that was posted to the backend, the request class has provided a file()
method.
class FooController extends Controller{public function bar(Request $request){$imageFile = $request->file("image");echo $imageFile["name"]; // image.jpeg}}
There are times where you may need to persist a variable through the request. For example, when you intend to pass any variables from the middleware to the controller method.
By using the setLocal() method, it is possible to persist such a variable until it reaches the destination of the route.
namespace Application\Middlewares;​use MightyCore\Middleware;use MightyCore\Vault\Routing\VerifyCsrf as RoutingVerifyCsrf;​class VerifyCsrf extends Middleware{public function administer(){$verifyCsrf = new RoutingVerifyCsrf();$verifyCsrf->verify();$this->request->setLocal("verified", true);}}
Notice that in the Middleware
class, the request class is already part of its property, under $this->request
.
At the destination, presumably the controller, you may retrieve back the variable as such:
class FooController extends Controller{// Redirecting to method based on www.example.com?foo=HelloWorldpublic function bar(Request $request){$local = $request->getLocal("verified");echo $local; // true}}
​