2012年10月25日 星期四

Symfony2 console commands

# Generate Bundle.
php app/console generate:bundle --namespace="My/Bundle" --format=yml
Doctrine

# Create database.
php app/console doctrine:database:create
# Generate Entity.
php app/console doctrine:generate:entity --entity="MyBundle:MyEntity"
# Generate Entities getters and setters.
php app/console doctrine:generate:entities MyBundle
# Update schema.
php app/console doctrine:schema:update --force
# Generate CRUD.
php app/console doctrine:generate:crud --entity="MyBundle:MyEntity"
Asset
# Install assets into web folder with symlink.
php app/console assets:install web --symlink

2012年10月24日 星期三

Doctrine以Composite及Foreign Keys作主鍵(Primary Key)

Doctrine2 可以用composite keys作為primary key(例如用戶的姓加名字作為主鍵), 而Doctrine2.1更支援關聯的foreign key.

方法很簡單:
  1. Entity內不能有@GeneratedValue, 除非設定為"ASSIGNED".
  2. 在需要作為primary key的property加上@Id這個annotation.
  3. 需要__construct() 方法在建立物件時傳入作為primary key的property, 因為primary key不是自動生成, 沒有primary key呼叫EntityManager#persist()會有問題.
<?php
use Doctrine\Common\Collections\ArrayCollection;

/** @Entity */
class Order
{
    /** @Id @Column(type="integer") @GeneratedValue */
    private $id;

    /** @ManyToOne(targetEntity="Customer") */
    private $customer;
    /** @OneToMany(targetEntity="OrderItem", mappedBy="order") */
    private $items;

    /** @Column(type="boolean") */
    private $payed = false;
    /** @Column(type="boolean") */
    private $shipped = false;
    /** @Column(type="datetime") */
    private $created;

    public function __construct(Customer $customer)
    {
        $this->customer = $customer;
        $this->items = new ArrayCollection();
        $this->created = new \DateTime("now");
    }
}

/** @Entity */
class Product
{
    /** @Id @Column(type="integer") @GeneratedValue */
    private $id;

    /** @Column(type="string") */
    private $name;

    /** @Column(type="decimal") */
    private $currentPrice;

    public function getCurrentPrice()
    {
        return $this->currentPrice;
    }
}

/** @Entity */
class OrderItem
{
    /** @Id @ManyToOne(targetEntity="Order") */
    private $order;

    /** @Id @ManyToOne(targetEntity="Product") */
    private $product;

    /** @Column(type="integer") */
    private $amount = 1;

    /** @Column(type="decimal") */
    private $offeredPrice;

    public function __construct(Order $order, Product $product, $amount = 1)
    {
        $this->order = $order;
        $this->product = $product;
        $this->offeredPrice = $product->getCurrentPrice();
    }
}
參考資料: http://docs.doctrine-project.org/projects/doctrine-orm/en/2.1/tutorials/composite-primary-keys.html