简体   繁体   中英

Symfony2 - How to use @Entity annotations in Controllers?

Symfony's manual on ParamConverter has this example:

/**
 * @Route("/blog/{post_id}")
 * @Entity("post", expr="repository.find(post_id)")
 */
public function showAction(Post $post)
{
}

Source: http://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/annotations/converters.html#fetch-via-an-expression

But using @Entity annotation gives me this error.

The annotation "@Entity" in method AppBundle\Controller\CurrencyController::currencyAction() was never imported. Did you maybe forget to add a "use" statement for this annotation?

Obviously, I need to use a namespace, but which one? Please help.

The Entity annotation only exist on master (or futur v4). Source file here

But as you can see, this is only a shortcut to @ParamConverter annotation with expr option, so you have to use this one until next release.

Best regards.

You are trying to use ParameterConverter so this syntax is just wrong.

Use this instead

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;

/**
 * @Route("/blog/{post_id}")
 * @ParamConverter("post_id", class="VendorBundle:Post")
 */
public function showAction(Post $post)
{
}

VendorBundle:Post should be replaced with whatever your Vendor is (if any) and Bundle is.

Using annotation @ParamConverter with option repository_method is deprecated

The repository_method option of @ParamConverter is deprecated and will be removed in 6.0. Use the expr option or @Entity.

Thus it's better to use @Entity (documentation)

You have to add the namespace :

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM