Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing generateURL() from Entity class

Tags:

symfony

I would like to access generateUrl in my entity class. You can access generateUrl in controller class like this:

$url = $this->generateUrl('your_route_name', array(/* parameters */));

Accoring do this article, I should try to 'create a service, and inject the router component in it'. Then I am reading Symfony Docs: Service Container and try configuration, but I still can not make it.

in app/config/config.yml

services:
    router:
        class: ???
        arguments: ???

How can I make router as service?

update

Why I want to use generateUrl in Entity class?

I am using Eko/FeedBundle. It requires to implements getFeedItemLink() in Entity. I need to give URL as return value of this function.

like image 302
whitebear Avatar asked Sep 12 '25 21:09

whitebear


1 Answers

The short answer is: you don't use the router inside entities and you don't create entities as services. You should create a separate service which is responsible for creating urls (if you wrote more about what you are trying achieve it would be simpler to give you more appropriate example).

For example:

use Symfony\Bundle\FrameworkBundle\Routing\Router;

class YourCustomUrlGenerator
{
    private $router;

    public function __construct(Router $router)
    {
        $this->router = $router;
    }

    public function generateUrl(YourEntity $entity)
    {
        // generate the url
    }
}

Then define your service for DIC:

services:
    custorm_url_generator:
        class: Namespace\YourCustomUrlGenerator
        arguments: [@router]
like image 192
Cyprian Avatar answered Sep 15 '25 20:09

Cyprian