master

laravel/framework

Last updated at: 29/12/2023 09:24

ViewController.php

TLDR

The ViewController.php file in the Illuminate\Routing namespace is a class that extends Controller. It is responsible for handling view rendering and returning the response.

Methods

__invoke

This method is invoked when an object of the ViewController class is treated as a function. It takes any number of arguments and merges them into the $args['data'] array. After that, it uses the response factory to create a response by rendering a view with the provided view name, data, status, and headers.

callAction

This method is responsible for executing an action on the controller. It takes a method name and an array of parameters. It calls the method with the provided parameters and returns the response.

Classes

None

<?php

namespace Illuminate\Routing;

use Illuminate\Contracts\Routing\ResponseFactory;

class ViewController extends Controller
{
    /**
     * The response factory implementation.
     *
     * @var \Illuminate\Contracts\Routing\ResponseFactory
     */
    protected $response;

    /**
     * Create a new controller instance.
     *
     * @param  \Illuminate\Contracts\Routing\ResponseFactory  $response
     * @return void
     */
    public function __construct(ResponseFactory $response)
    {
        $this->response = $response;
    }

    /**
     * Invoke the controller method.
     *
     * @param  mixed  ...$args
     * @return \Illuminate\Http\Response
     */
    public function __invoke(...$args)
    {
        $routeParameters = array_filter($args, function ($key) {
            return ! in_array($key, ['view', 'data', 'status', 'headers']);
        }, ARRAY_FILTER_USE_KEY);

        $args['data'] = array_merge($args['data'], $routeParameters);

        return $this->response->view(
            $args['view'],
            $args['data'],
            $args['status'],
            $args['headers']
        );
    }

    /**
     * Execute an action on the controller.
     *
     * @param  string  $method
     * @param  array  $parameters
     * @return \Symfony\Component\HttpFoundation\Response
     */
    public function callAction($method, $parameters)
    {
        return $this->{$method}(...$parameters);
    }
}