【问题标题】:exception `Unable to find entity` after the addition of FOSUserBundle添加 FOSUserBundle 后出现异常“无法找到实体”
【发布时间】:2015-01-22 11:51:57
【问题描述】:

我按照书中的步骤进行操作(基于 symfony 2.0.10,我正在使用 Symfony2.6.1 和 FOSUB 2.0)。

我使用 CRUD 构建项目,可以很好地显示来自 db 的数据(My/BackendBundle 中的山地控制器)。

然后我只想为登录的用户管理员显示项目(使用 ROLE_SUPER_ADMIN,存在于我的 for_user 表中的数据库中,带有 CRUD 数据)。

但是当打开 ../web/ 时,它的结果异常 Unable to find Mountain entity。来自山地控制器 showAction($id)

#\src\My\BackendBundle\Controller\MountainController.php
/**
 * Finds and displays a Mountain entity.
 *
 * @Route("/{id}", name="mountain_show")
 * @Method("GET")
 * @Template()
 */
public function showAction($id)
{
    $em = $this->getDoctrine()->getManager();

    $entity = $em->getRepository('MyBackendBundle:Mountain')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Mountain entity.');
    }

    $deleteForm = $this->createDeleteForm($id);

    return array(
        'entity'      => $entity,
        'delete_form' => $deleteForm->createView(),
    );

AppKernel.php

#\app\AppKernel.php
    new FOS\UserBundle\FOSUserBundle(),
    new My\UserBundle\MyUserBundle(),
    new My\BackendBundle\MyBackendBundle(),

security.yml

#\app\config\security.yml
security:
    providers:
        fos_userbundle:
            id: fos_user.user_manager

    encoders:
        FOS\UserBundle\Model\UserInterface: sha512

    firewalls:
        main:
            pattern: ^/
            logout:       true
            anonymous:    true
            form_login:
                provider:                       fos_userbundle
                csrf_provider:                  form.csrf_provider
                login_path:                     /login
                use_forward:                    false
                check_path:                     /login_check
                post_only:                      true
                always_use_default_target_path: false
                default_target_path:            /
                target_path_parameter:          _target_path
                use_referer:                    false
                failure_path:                   null
                failure_forward:                false
                username_parameter:             _username
                password_parameter:             _password
                csrf_parameter:                 _csrf_token
                intention:                      authenticate

    access_control:
        - { path: ^/login$, role: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/, role: ROLE_SUPER_ADMIN }

config.yml

#\app\config\config.yml
imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: services.yml }

framework:
    #esi:             ~
    translator:      ~
    secret:          "%secret%"
    router:
        resource: "%kernel.root_dir%/config/routing.yml"
        strict_requirements: ~
    form:            ~
    csrf_protection: ~
    validation:      { enable_annotations: true }
    templating:
        engines: ['twig']
        #assets_version: SomeVersionScheme
    default_locale:  "%locale%"
    trusted_hosts:   ~
    trusted_proxies: ~
    session:
        # default_locale: pl
        # handler_id set to null will use default session handler from php.ini
        handler_id:  ~
    fragments:       ~
    http_method_override: true

# Twig Configuration
twig:
    debug:            "%kernel.debug%"
    strict_variables: "%kernel.debug%"

# Assetic Configuration
assetic:
    debug:          "%kernel.debug%"
    use_controller: false
    bundles:        [ ]
    #java: /usr/bin/java
    filters:
        cssrewrite: ~
        #closure:
        #    jar: "%kernel.root_dir%/Resources/java/compiler.jar"
        #yui_css:
        #    jar: "%kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar"

# Doctrine Configuration
doctrine:
    dbal:
        driver:   "%database_driver%"
        host:     "%database_host%"
        port:     "%database_port%"
        dbname:   "%database_name%"
        user:     "%database_user%"
        password: "%database_password%"
        charset:  UTF8
        # if using pdo_sqlite as your database driver:
        #   1. add the path in parameters.yml
        #     e.g. database_path: "%kernel.root_dir%/data/data.db3"
        #   2. Uncomment database_path in parameters.yml.dist
        #   3. Uncomment next line:
        #     path:     "%database_path%"

    orm:
        auto_generate_proxy_classes: "%kernel.debug%"
        auto_mapping: true

# Swiftmailer Configuration
swiftmailer:
    transport: "%mailer_transport%"
    host:      "%mailer_host%"
    username:  "%mailer_user%"
    password:  "%mailer_password%"
    spool:     { type: memory }


stof_doctrine_extensions:
    default_locale: en_US
    orm:
        default:
            tree: false
            loggable: false
            timestampable: false
            sluggable: false
            translatable: false

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: My\UserBundle\Entity\User

routing.yml

#\app\config\routing.yml
MyBackendBundle:
    resource: "@MyBackendBundle/Controller/"
    type:     annotation
    prefix:   /

fos_user_security:
    resource: "@FOSUserBundle/Resources/config/routing/security.xml"

parameters.yml

#\parameters.yml
parameters:
    database_driver: pdo_mysql
    database_host: 127.0.0.1
    database_port: null
    database_name: koronaziemi
    database_user: root
    database_password: null
    mailer_transport: smtp
    mailer_host: 127.0.0.1
    mailer_user: null
    mailer_password: null
    locale: pl
    secret: ThisTokenIsNotSoSecretChangeIt

【问题讨论】:

  • 对SF2不太熟悉,但对SF1,在任何模型更改后我总是要清除缓存。
  • var_dump($id); 就在$entity = $em->getRepository('MyBackendBundle:Mountain')->find($id); 之前。仔细检查它是否存在于数据库中。
  • @Mike Purcell 我每次都清除缓存。
  • @Aistis var_dump($id); 显示 string 'login' (length=5) 。当他将localhost/project/web/ 重定向到localhost/project/web/login 时,他从URL 中得到了这个。我是初学者,我仍然不明白那是什么意思。
  • 这个routing.yml(来自主帖)看起来正确吗?

标签: php symfony fosuserbundle


【解决方案1】:

requirements 参数添加到您的路由描述中,您也可以跳过实体获取,让 Symfony 为您服务:

#\src\My\BackendBundle\Controller\MountainController.php
/**
 * Finds and displays a Mountain entity.
 *
 * @Route("/{mountain}", name="mountain_show", requirements={"mountain": "\d+"})
 * @Method("GET")
 * @Template()
 */
public function showAction(Mountain $mountain)
{
    $deleteForm = $this->createDeleteForm(mountain->getId());

    return array(
        'entity'      => $mountain,
        'delete_form' => $deleteForm->createView(),
    );
}

另外,@Template() 被认为是不好的做法,最好返回 Response 对象:

#\src\My\BackendBundle\Controller\MountainController.php
/**
 * Finds and displays a Mountain entity.
 *
 * @Route("/{mountain}", name="mountain_show", requirements={"mountain": "\d+"})
 * @Method("GET")
 */
public function showAction(Mountain $mountain)
{
    $deleteForm = $this->createDeleteForm(mountain->getId());

    return $this->render(
        'MyBackendBundle:Mountain:show',
        array(
            'entity'      => $mountain,
            'delete_form' => $deleteForm->createView(),
        )
    );
}

【讨论】:

  • 是否有必要将id 替换为mountain?这将导致与view 相关的许多其他异常以及需要id 的其他操作,例如editAction。这所有的Moutain Controller都是由命令CRUD生成的,为什么要纠正这个。
  • 不是!只需尝试在操作注释中添加requirements 参数即可。
  • 这个requirements 技巧有效!我选择它作为答案,但我确定解决问题的关键在于 conf 文件。为什么他得到/login作为参数?
  • 我的猜测:相同的/ 路径被覆盖。我的意思是,您被重定向登录,但登录路径被操作路由覆盖。添加requirements 我们创建了一个更具体的路由规则,所以它不再重叠。在我的实践中,通常 URL 会变成 /mountain/{id},但这取决于您的需求。
  • 本书的作者跳过了他将@Route("/{id}"修改为@Route("/{id}/show"的步骤,并且没有提及。这是一本作者描述每一步的书。这就是为什么我开始在 conf 文件中查找原因,并专注于这本 2012 年的书所描述的可能过时的 symfony 版本。现在它很清楚和简单。感谢您的宝贵时间。
【解决方案2】:

----编辑---

@Aistis 使用此代码

 /**
 * @Route("/{id}", name="mountain_show", requirements={"id": "\d+"}))
 * @Template()
 */
public function showAction($id)
{
    $em = $this->getDoctrine()->getManager();
    var_dump($id);
    $entity = $em->getRepository('MyBackendBundle:Mountain')->find($id);

    if (!$entity) {
        throw $this->createNotFoundException('Unable to find Mountain entity.');
    }

    $deleteForm = $this->createDeleteForm($id);

    return array(
        'entity'      => $entity,
        'delete_form' => $deleteForm->createView(),
    );
}

它的作品。但是为什么他得到/login作为参数呢?

【讨论】:

  • 动作参数中不必使用Mountain。我只是给了一个建议 :) 无论如何,您的原始代码应该只使用注释中添加的 requirements 参数。不过,我不确定security.yml 配置。附言我不喜欢 Symfony 2.3 CRUD 生成。如何实现它取决于您。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-20
  • 1970-01-01
  • 2012-09-01
  • 1970-01-01
  • 2018-08-03
相关资源
最近更新 更多