設定ファイルを指定してzfコマンドを実行する
[]

2010.12.15

このエントリーをはてなブックマークに追加
はてなブックマーク - 設定ファイルを指定してzfコマンドを実行する

$ export ZF_CONFIG_FILE=./.zf.ini
$ php scripts/zf show config
User Configuration: ./.zf.ini
  |-- php
  |   `-- include_path: /Users/yokada/work/web/49283/site/pragma/libs:.
  |-- basicloader
  |   `-- classes
  |       |-- 1: Pragma_Tool_Provider_Hello
  |       `-- 2: Pragma_Tool_Provider_Doctrine
  `-- basePath: /Users/yokada/work/web/49283/site

または、一行で、

$ ZF_CONFIG_FILE=./.zf.ini zf show config

指定した設定ファイルが無ければ、HOMEディレクトリ(ZF_HOME、HOME、HOMEPATH、USERPROFILE)の環境変数のパスにある .zf.ini が読み込まれる。

ブートストラップでリクエストを初期化する
[]

2010.12.14

このエントリーをはてなブックマークに追加
はてなブックマーク - ブートストラップでリクエストを初期化する

デフォルトではリクエストオブジェクトはFrontControllerによるディスパッチループの本体であるdispatchメソッドで初期化されるが、ブートストラップでリクエストオブジェクトを利用して、URLごとに処理を振り分けたい場合に。

モジュールを使わない場合

application/Bootstrap.php でリクエストオブジェクトを初期化する

<?php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
  protected function _initRequest()
  {
    $request = new Zend_Controller_Request_Http();
    Zend_Controller_Front::getInstance()->getRouter()->route($request);
    var_dump($request);
    /**
     * /a/b/c をリクエストした場合
     *
    object(Zend_Controller_Request_Http)[10]
      protected '_paramSources' =>
      array
        0 => string '_GET' (length=4)
        1 => string '_POST' (length=5)
      protected '_requestUri' => string '/a/b/c' (length=6)
      protected '_baseUrl' => string '' (length=0)
      protected '_basePath' => null
      protected '_pathInfo' => string '/a/b/c' (length=6)
      protected '_params' =>
      array
        'controller' => string 'a' (length=1)
        'action' => string 'b' (length=1)
        'module' => string 'default' (length=7)
      protected '_rawBody' => null
      protected '_aliases' =>
      array
        empty
      protected '_dispatched' => boolean false
      protected '_module' => string 'default' (length=7)
      protected '_moduleKey' => string 'module' (length=6)
      protected '_controller' => string 'a' (length=1)
      protected '_controllerKey' => string 'controller' (length=10)
      protected '_action' => string 'b' (length=1)
      protected '_actionKey' => string 'action' (length=6)
    */

  }
}

モジュールを使う場合(Aというモジュールを例とする)

application/modules/a/Bootstrap.php でリクエストオブジェクトを初期化する。

<?php

class A_Bootstrap extends Zend_Application_Module_Bootstrap
{
  protected function _initModuleRequest()
  {
    $request = new Zend_Controller_Request_Http();
    Zend_Controller_Front::getInstance()->getRouter()->route($request);
    var_dump($request);
    /**
     * /a/b/cをリクエストした場合
     *
    object(Zend_Controller_Request_Http)[31]
      protected '_paramSources' =>
      array
        0 => string '_GET' (length=4)
        1 => string '_POST' (length=5)
      protected '_requestUri' => string '/a/b/c' (length=6)
      protected '_baseUrl' => string '' (length=0)
      protected '_basePath' => null
      protected '_pathInfo' => string '/a/b/c' (length=6)
      protected '_params' =>
      array
        'module' => string 'a' (length=1)
        'controller' => string 'b' (length=1)
        'action' => string 'c' (length=1)
      protected '_rawBody' => null
      protected '_aliases' =>
      array
        empty
      protected '_dispatched' => boolean false
      protected '_module' => string 'a' (length=1)
      protected '_moduleKey' => string 'module' (length=6)
      protected '_controller' => string 'b' (length=1)
      protected '_controllerKey' => string 'controller' (length=10)
      protected '_action' => string 'c' (length=1)
      protected '_actionKey' => string 'action' (length=6)
     */

  }
}

モジュールを使う場合は、実際は自分用のモジュールブートストラップ(MyModuleBootstrap extends Zend_Application_Module_Bootstrap) を作成して、そこに初期化処理を書くことになると思う。

zend framework + doctrine メモ
[]

2010.11.27

このエントリーをはてなブックマークに追加
はてなブックマーク - zend framework + doctrine メモ

directory map

myproject
|-- logs
|   |-- access_log
|   `-- error_log
|-- pragma
|   |-- Bootstrap.php
|   |-- configs
|   |-- doctrine
|   |   |-- fixtures
|   |   |-- migrations
|   |   |-- models
|   |   |-- schema
|   |   `-- sql
|   |-- libs
|   |   |-- Doctrine -> ../vendors/doctrine/lib/Doctrine
|   |   |-- Doctrine.php -> ../vendors/doctrine/lib/Doctrine.php
|   |   |-- Pragma
|   |   |-- Pragma.php
|   |   `-- Zend
|   |-- modules:サービス境界
|   |-- scripts
|   |   `-- doctrine.php
|   |-- var
|   `-- vendors
|       `-- doctrine
|-- public
`-- tests

Doctrine-CLI

myproject/pragma/scripts/doctrine.php

#!/Applications/MAMP/bin/php5/bin/php

<?php

defined('BASE_PATH')
  || define('BASE_PATH', realpath(dirname(__FILE__) . '/../..'));

defined('APP_PATH')
  || define('APP_PATH', BASE_PATH . '/pragma');

set_include_path(
  implode(PATH_SEPARATOR, array(
    APP_PATH . '/libs'
    , APP_PATH . '/libs/Doctrine/Parser/sfYaml'
    , get_include_path()
  )
));

defined('APP_ENV')
  || define('APP_ENV', (getenv('APP_ENV') ? getenv('APP_ENV') : 'production'));

require 'Zend/Loader/Autoloader.php';
$loader = Zend_Loader_Autoloader::getInstance();
$loader->setFallbackAutoloader(true);

$res = new Zend_Loader_Autoloader_Resource(array(
  'basePath'  => APP_PATH."/doctrine"
  , 'namespace' => "Orm"
));
$res->addResourceTypes(array(
  'model' => array(
    'path' => "models"
    , 'namespace' => 'Model'
  )
));

//var_dump(Zend_Loader_Autoloader::getInstance()->getAutoloaders());
Doctrine_Manager::connection("mysql://root:root@localhost/pragma_cms");
$cli = new Doctrine_Cli(array(
  'data_fixtures_path' =>  APP_PATH.'/doctrine/data/fixtures'
  , 'models_path' =>  APP_PATH.'/doctrine/models'
  , 'migrations_path' =>  APP_PATH.'/doctrine/migrations'
  , 'sql_path' =>  APP_PATH.'/doctrine/sql'
  , 'yaml_schema_path' =>  APP_PATH.'/doctrine/schema'
  , 'generate_models_options' => array(
    'classPrefix' => 'Orm_Model_'
    , 'classPrefixFiles' => false // classPrefixと同じディレクトリ階層にクラスを生成するか?
    , 'generateTableClasses' => true
    , 'baseClassesDirectory' => null
    //, 'baseClassPrefix' => 'Base_'
    //, 'pearStyle' => true
  )
));
$cli->run($_SERVER['argv']);

myproject/doctrine/schema/message.yml

---
Message:
    columns:
        id:
            primary: true
            autoincrement: true
            type: integer(4)
        posted:
            type: timestamp
        name:
            type: string(255)
        message:
            type: string

Doctrine-CLI を実行してyamlからモデルを生成する

$ php scripts/doctrine.php generate-models-yaml
generate-models-yaml - Generated models successfully from YAML schema

$ tree doctrine/models/
doctrine/models/
|-- BaseMessage.php
|-- Message.php
`-- MessageTable.php

テーブルを生成するSQLを生成する

$ php scripts/doctrine.php generate-sql
generate-sql - Generated SQL successfully for models

$ tree doctrine/sql/

doctrine/sql/
`-- schema.sql

データベースにテーブルを作成する

$ php scripts/doctrine.php create-tables
create-tables - Created tables successfully

Create Doctrine application resource

モジュールに応じてレイアウトを切り替えるプラグインのサンプル
[]

2010.11.21

このエントリーをはてなブックマークに追加
はてなブックマーク - モジュールに応じてレイアウトを切り替えるプラグインのサンプル

コントローラープラグイン内で現在のモジュールブートストラップのオプションを取得し、モジュールごとに初期化処理を切り替えたい場合。

カスタムモジュールブートストラップ:Zend_Application_Module_Bootstrap を拡張し設定ファイルを取得して自身にセットする。

<?php
class Pragma_Application_Module_Bootstrap extends Zend_Application_Module_Bootstrap
{
  protected function _initModuleConfig()
  {
    $configPath = APP_PATH
      . '/modules/'
      . strtolower($this->getModuleName())
      . '/configs/module.ini'
    ;
   
    if(file_exists($configPath)){
      $config = new Pragma_Config_Ini($configPath, APP_ENV);
      $this->setOptions($config->toArray());
    }
  }
}

サンプルプラグイン:モジュールに応じてレイアウト切り替える。

<?php

class Pragma_Controller_Plugin_LayoutSwitcher extends Zend_Controller_Plugin_Abstract
{
  public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
  {
    $layout = Zend_Layout::getMvcInstance();
    if(isset($layout) == false || $layout->isEnabled() == false ){
      return;
    }
   
    // get module bootstrap.
    $bootstrap = Zend_Controller_Front::getInstance()
      ->getParam('bootstrap')
      ->getResource('modules')
      ->{$request->getModuleName()}
    ;
   
    if(isset($bootstrap) == false){
      return;
    }
   
    $options = Pragma_Util_Array::get($bootstrap->getOptions(), 'layoutSwitcher');
   
    if(isset($options['layoutpath'])){
      $layout->setLayoutPath($options['layoutpath']);
    }
   
    if(isset($options['layout'])){
      $layout->setLayout($options['layout']);
    }
  }}

設定ファイル例:APP_PATH/modules/mymodule/configs/module.ini

layoutSwitcher.layoutpath = APP_PATH "/modules/mymodule/views/layouts"
layoutSwitcher.layout = "layout"

これで例えば、/mymodule/home/index にアクセスすると、APP_PATH/modules/mymodule/configs/module.ini に設定されているレイアウトを描画するようにできる。

現在のモジュールブートストラップを特定するのに手間取った。当初ブートストラップ側で、リクエストを取得しようと考えたが、リクエストのパースが完了するのは、フロントコントローラのディスパッチ時なので、結局、コントローラプラグインのdispatchLoopStartupに渡される request オブジェクトでパース済のモジュール/コントローラ/アクション/パラメタ を取得するようにした。

Zend_Configで配列をさくっとマージする
[]

2010.05.20

このエントリーをはてなブックマークに追加
はてなブックマーク - Zend_Configで配列をさくっとマージする

配列base の a を d にアップデートするシンプルな例。

<?php
require_once 'Zend/Config.php';
$base = array(
    'a','b','c'
);
$update = array(
    'd'
);
$baseConf = new Zend_Config( $base, array('allowModifications'=>true) );
$updateConf = new Zend_Config($update);
print_r( $baseConf->merge($updateConf)->toArray() );
/**
Array
(
    [0] => d
    [1] => b
    [2] => c
)
 */

多次元配列もなんのその

<?php

require_once 'Zend/Config.php';

$base = array(
    'base0',
    'baseKey1' => 'baseVal1',
    array(1,2,3)
);

$update = array(
    'update0',
    'updateKey1' => 'updateVal1',
    array(
        1,
        array('b','c','d')
    )
);

$baseConf = new Zend_Config( $base, array('allowModifications'=>true) );
$updateConf = new Zend_Config($update);
print_r( $baseConf->merge($updateConf)->toArray() );
/**
Array
(
    [0] => update0
    [baseKey1] => baseVal1
    [1] => Array
        (
            [0] => 1
            [1] => Array
                (
                    [0] => b
                    [1] => c
                    [2] => d
                )

            [2] => 3
        )

    [updateKey1] => updateVal1
)
*/

リソースを好きなところに配置して自動ロード可能にする
[]

2010.05.18

このエントリーをはてなブックマークに追加
はてなブックマーク - リソースを好きなところに配置して自動ロード可能にする

例として、モジュラーディレクトリ構造を使いつつも、site/application/modules/mymodule 以下にformsやmodelsを配置するのではなく、一つ上の、site/application/ 以下に配置したいという場合。


> 続きを読む

Zend_Filter_Inputに渡す定義をZend_Config_Ini形式で組み立てる
[]

2010.04.21

このエントリーをはてなブックマークに追加
はてなブックマーク - Zend_Filter_Inputに渡す定義をZend_Config_Ini形式で組み立てる

Zend_Filter_Inputに渡すバリデートをINI形式で定義する場合。


> 続きを読む

Zend Framework 1.8.4 処理フロー
[]

2010.04.08

このエントリーをはてなブックマークに追加
はてなブックマーク - Zend Framework 1.8.4 処理フロー


> 続きを読む

Zend_Db_Table->describeTableでエラー
[]

2009.10.14

このエントリーをはてなブックマークに追加
はてなブックマーク - Zend_Db_Table->describeTableでエラー

環境

  • フロント:RHEL5
  • バックエンド: DB2 on System i5
  • DB2 Connect Product
  • ドライバ:Ibm_Db2

フロントはlinuxでバックエンドがi5上で動いているDB2の場合。Zend_Db_Tableを使うと以下のエラーが出た。


> 続きを読む

Zend Framework メモ
[]

2009.10.12

このエントリーをはてなブックマークに追加
はてなブックマーク - Zend Framework メモ

環境

  • PHP 5.2.11
  • Zend Framework 1.8.5
  • jQuery 1.3.2

Zend公式リファレンス

ZFコマンド

zf create project

プロジェクト作成

$ zf create project MyProject1
Creating project at /Users/yokada/MyProject1

出来上がるファイル構成

- MyProject1 /
    - .zfproject.xml
    - application /
        - Bootstrap.php
        - configs /
            - application.ini
        - controllers
            - ErrorController.php
            - IndexController.php
        - models
        - views
            - helpers /
            - scripts /
            - error /
                - error.phtml
            - index /
                - index.phtml
    - library /
    - public /
        - .htaccess
        - index.php
    - tests /
        - application
        - bootstrap.php
    - library /
        - bootstrap.php
        - phpunit.xml

モジュラーディレクトリ構成

ファイルレイアウト

以下、この構成を参照して説明する。

- MyProject1 /
    - application /
        - Bootstrap.php
        - configs /
                - application.ini
        - layouts /
        - modules /
            - default /
                - Bootstrap.php:モジュールブートストラップ
                - controllers /
                - models /
                - views /
    - library /:ライブラリ
        - Yokada /
    - public /
        - index.php


> 続きを読む