Symfony2 入門という事で、とりあえずブログチュートリアル的な事をはじめようかと思います。

CakePHP と何が違うの?

  • オブジェクト間のデータ受け渡しが配列からオブジェクトになる
  • 連想配列のタイポ等のミスがなくなる
  • そもそも連想配列の構造を覚える必要がなくなる
  • タイプヒンティングが使えるのでIDEとの親和性が高い

  • DI(DependencyInjection)が組み込まれている
  • 疎結合
  • なのでテストがしやすい
  • そのうえコンポーネントも豊富
  • しかもコンポーネントの動作も変更する事ができる
  • 更にはフレームワークの動作までも変更する事ができる
  • if (Config::read('debug') === 2) {} とか訳の分からないコードを書かなくても良い。

  • 他にも
  • Doctrine(ORM)
  • 様々な抽象レイヤー(関心の分離)
  • などなど…

他にもたくさんありますが、とりあえずこんなところです。

早速インストール

用意するもの

  • Mac
  • HomeBrew
  • PHP 5.3.9~
  • MySQL もしくは MariaDB

プロジェクトのセットアップ

公式のインストーラーであるSymfony Installerが用意されています。
Composerを利用した場合より短時間&簡単にセットアップすることが出来ます。

Symfony Installerの準備

$ sudo curl -LsS http://symfony.com/installer -o /usr/local/bin/symfony
$ sudo chmod a+x /usr/local/bin/symfony

プロジェクトのインストール

$ cd PATH_TO_WEBROOT
$ symfony new symfony-blog-tuts lts

Symfonyコマンドを利用して、アプリケーションを起動します。

$ cd symfony-blog-tuts
$ php app/console server:run

DBの設定を行います。

# app/config/parameters.yml

  parameters:
      database_host: 127.0.0.1
      database_port: null
-     database_name: symfony
-     database_user: root
+     database_name: sfblogtuts
+     database_user: sfblog
      database_password: null
      mailer_transport: smtp
      mailer_host: 127.0.0.1
      mailer_user: null
      mailer_password: null
      secret: 9920fd28a31c23290e9b11c264d8b1132fb8e296

忘れないうちにデータベースをセットアップします。

mysql -uroot -p
Enter password:
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 25
Server version: 5.6.26 Homebrew

Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> create database sfblogtuts default character set utf8;
Query OK, 1 row affected (0.03 sec)

mysql> create user sfblog@localhost identified by 'sfblog';
Query OK, 0 rows affected (0.00 sec)

mysql> grant all privileges on sfblogtuts.* to sfblog@localhost;
Query OK, 0 rows affected (0.03 sec)

mysql>

ブラウザで http://localhost:8000 を開きます。

symfony2-welcome-image

この画面が出ればセットアップはひとまず終了です。 ちなみに 下に表示されているツールバーの様な物 は Symfony Profiler という便利なやつです。 CakePHPのDebugToolbarとは違い凄まじく高機能です。