0

我对 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"
}

我今天更新了。

问题出在哪里?

4

2 回答 2

1

当我自动生成我的实体时,例如:

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

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

当我删除 yml 一切正常

于 2013-10-25T13:53:10.697 回答
0

如果你使用 YMAL (metadate) 你不需要写注释

@ORM\HasLifecycleCallbacks()

在您的 Entity 类的顶部并编写注释

@ORM\PrePersist

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

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

lifecycleCallbacks:
    prePersist: [addTitleSuffix]   

就像在Symfony 2 文档中一样

于 2013-11-19T14:31:15.583 回答