对我来说是新的一天:D
我覆盖了路由器和 UrlGenerator。
@Chausser:我用一个简单的方法解决了你的问题 1:
acme_demo_example:
resource: "@AcmeDemoBundle/Controller/"
type: annotation
prefix: /{user}
现在我有这样的路线。
_welcome ANY ANY ANY /
acmedemo_example_index ANY ANY ANY /{user}/acme/demos
acmedemo_example_edit ANY ANY ANY /{user}/acme/edit/{id}
acmedemo_example_delete ANY ANY ANY /{user}/acme/delete/{id}
acmeapi_examples_get GET ANY ANY /api/acme
acmeapi_examples_edit POST ANY ANY /api/acme
问题 1 已解决!
现在问题 2,因为我不想要额外的路由功能或其他东西。
我想使用<a href="{{ path('acmedemo_example_index') }}">Show demos</a> 和<a href="{{ path('acmedemo_example_edit', {id: entity.id}) }}">Edit demo</a>。
但如果我使用它,我会得到错误。
也让我们这样做。
这个服务的问题是我没有容器>.
services.yml
parameters:
router.class: Acme\DemoBundle\Routing\Router
router.options.generator_base_class: Acme\DemoBundle\Routing\Generator\UrlGenerator
Acme\DemoBundle\Routing\Router
use Symfony\Bundle\FrameworkBundle\Routing\Router as BaseRouter;
class Router extends BaseRouter implements ContainerAwareInterface
{
private $container;
public function __construct(ContainerInterface $container, $resource, array $options = array(), RequestContext $context = null)
{
parent::__construct($container, $resource, $options, $context);
$this->setContainer($container);
}
public function getGenerator()
{
$generator = parent::getGenerator();
$generator->setContainer($this->container);
return $generator;
}
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
}
Acme\DemoBundle\Routing\Generator\UrlGenerator
use Symfony\Component\Routing\Generator\UrlGenerator as BaseUrlGenerator;
class UrlGenerator extends BaseUrlGenerator implements ContainerAwareInterface
{
private $container;
protected function doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens)
{
/** Set the default user parameter for the routes which haven't a user parameter */
if(preg_match('/^acmedemo_/i', $name) && in_array('user', $variables) && !array_key_exists('user', $parameters))
{
$parameters['user'] = $this->getUser()->getId();
}
return parent::doGenerate($variables, $defaults, $requirements, $tokens, $parameters, $name, $referenceType, $hostTokens);
}
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* @see \Symfony\Component\Security\Core\Authentication\Token\TokenInterface::getUser()
*/
public function getUser()
{
if (!$this->container->has('security.context')) {
throw new \LogicException('The SecurityBundle is not registered in your application.');
}
if (null === $token = $this->container->get('security.context')->getToken()) {
return null;
}
if (!is_object($user = $token->getUser())) {
return null;
}
return $user;
}
}
问题 2 已解决!
(我在 Symfony 上编写的代码*2.3*)
感谢您的帮助。但我认为这样更好 =)