Pass functions or get routes url directly inside phpview

Hi,

I have three little questions :

1 - I wanted to know if there is a way to pass certain functions directly into the phpview to use these functions in the view? (custom functions that work with multilingual to get the current URL, or also route the URL from name that use the routeParser for example).

2 - Can I pass the $request object to the php view (because these functions need the $request object to work)?
I saw that a similar function exists for the Twig view to get the route URL directly from the view, but I’m currently using PHP-View for Slim.

I was thinking of passing the $request object to the phpview with middleware with the addAttribute method like this:

public function __invoke(RequestInterface $request, RequestHandlerInterface $handler): Response
      {
          $this->phpView->addAttribute('request', $request);
}

And then call my custom functions, or if that’s not possible, directly call $routeParser from the view like this:

$routeParser = RouteContext::fromRequest($request)->getRouteParser();
$routeParser->urlFor('my_route_name');

I was wondering if it is ok to send the $request object like this to the view?

3 - Why do we need the $request object to get the URL of other routes? (I was just thinking that some other frameworks don’t ask the $request object for this)

Thanks for your help

Hi :slight_smile:

  1. Passing custom functions is technically possible, but maybe try to check what specific feature you need and pass only the needed data if possible. If you need a translation function, such as __(), then you could register this function using composer.
    "autoload": {
        "files": [
            "src/Support/functions.php"
        ]
    },
  1. Passing the $request object to your views is possible, but it’s not a common practice. It’s generally recommended to keep views as simple as possible and avoid tightly coupling them with the request object.
    It’s usually better to extract the required data from the $request object in your route handlers or middleware and then pass that data to your views. This approach keeps your views clean and decoupled from the request object, making them more maintainable and testable.

  2. The $request object is used to generate URLs (using the RouteParser) for other routes because it contains information about the current request, including the base path, query parameters, and other context-specific data. This is important for building links that work correctly, especially in cases where your application is hosted on a subdirectory.

Thanks for your answer odan :slight_smile:

1 Like