生命周期回调在我的Symfony 2.3.6新项目中不起作用

时间:2013-10-21 07:19:57

标签: php symfony doctrine-orm doctrine symfony-2.3

我不是Symfony的新手,我在2.0到2.3的多个项目中工作,并且我成功地使用了几次生命周期回调。

现在我安装最新的Symfony 2.3.6,如:

php composer.phar create-project symfony/framework-standard-edition path/ 2.3.6

我总是在任何地方使用注释。

我在我的实体顶部添加了很好的注释:

<?php

namespace Myproject\AdminBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Category
 *
 * @ORM\Table(name="category")
 * @ORM\HasLifecycleCallbacks()
 * @ORM\Entity
 */
class Category
{

PrePersist 注释:

/**
* @ORM\PrePersist
*/
public function addTitleSuffix() 
{
    $this->title = $this->title . '--test';
}

我做了几次书面测试

@ORM\HasLifecycleCallbacks

@ORM\PrePersist()

或在PrePersist中添加退出而不起作用:(

我的实体很好地坚持我的mysql数据库,但没有输入我的prepersist方法。

我的控制器是用crud生成的。

我的插入方法是:

/**
 * Creates a new Category entity.
 *
 * @Route("/", name="category_create")
 * @Method("POST")
 * @Template()
 */
public function createAction(Request $request)
{
    $entity = new Category();
    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $em->persist($entity);
        $em->flush();

        return $this->redirect($this->generateUrl('category_show', array('id' => $entity->getId())));
    }

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

来自我的composer.json

"require": {
    "php": ">=5.3.3",
    "symfony/symfony": "2.3.*",
    "doctrine/orm": ">=2.2.3,<2.4-dev",
    "doctrine/doctrine-bundle": "1.2.*",
    "twig/extensions": "1.0.*",
    "symfony/assetic-bundle": "2.3.*",
    "symfony/swiftmailer-bundle": "2.3.*",
    "symfony/monolog-bundle": "2.3.*",
    "sensio/distribution-bundle": "2.3.*",
    "sensio/framework-extra-bundle": "2.3.*",
    "sensio/generator-bundle": "2.3.*",
    "incenteev/composer-parameter-handler": "~2.0",
    "friendsofsymfony/jsrouting-bundle": "~1.1",
    "knplabs/knp-paginator-bundle": "dev-master"
}

我今天更新了。

问题出在哪里?

2 个答案:

答案 0 :(得分:1)

当我自动生成我的实体时:

php app/console doctrine:mapping:import --force AcmeBlogBundle yml

它生成yml,yml优先于实体上的注释。

当我删除yml时,一切正常

答案 1 :(得分:0)

如果您使用YMAL(元数据),则不需要编写注释

@ORM\HasLifecycleCallbacks()

位于Entity类的顶部  并编写注释

@ORM\PrePersist

在您需要执行pre persist的方法之上

JUST 在YMAL文件中写出您的方法名称,如下所示:

lifecycleCallbacks:
    prePersist: [addTitleSuffix]   

Documentation Of Symfony 2