開発メモ

開発用のメモです。

Silex / DB 接続

<?php

namespace TestApp;

    class Application extends \Silex\Application {

        /**
        * @var TestApp\Application
        */
        var $app;

        public function __construct( ) {
            parent::__construct( );

            $app = &$this;

            // load config
            $app[ 'config' ] = $app->share( function( ) {
                $config = \Symfony\Component\Yaml\Yaml::parse( dirname( $_SERVER[ "CONTEXT_DOCUMENT_ROOT" ] ) . '/config/config.yml' );

                function change( &$config ) {
                    // ループを再帰的に行い、 文字列 : __DIR__ を 定数 dirname( __FILE__ ) へ 展開する
                    foreach( $config as $keyname => $value ) {
                        if( empty( $config[ $keyname ] ) ) {
                            return;
                        } elseif( is_array( $config[ $keyname ] ) ) {
                            change( $config[ $keyname ] );
                        } ELSEIF( is_string( $config[ $keyname ] ) ) {
                            $config[ $keyname ] = str_replace( '\\', '/', str_replace( '__DIR__', dirname( __FILE__ ), $value ) );
                        }
                    }
                }

                change( $config );

                foreach( $config['ormOptions']['mappings']['path'] as $key => $value ) {
                    // __DIR__ を展開
                    $value = str_replace( '\\', '/', str_replace( '__DIR__', dirname( __FILE__ ), $value ) );
                    $config[ 'ormOptions' ][ 'mappings' ][ 'path' ][ $key ] = $value;
                }
                return $config;
            } );

            // twig 対応 start
            $app->register( new \Silex\Provider\TwigServiceProvider( ), array(
            // @formatter:off 
                'debug' => $app[ 'config' ]['debug'], 
                'twig.path' => array( 
                    dirname(__FILE__). '/Templates' ), 
                ) 
            // @formatter:on
            );
            // twig 対応 end

            // database connection configuret start
            $app->register( new \Silex\Provider\DoctrineServiceProvider( ), array( 'db.options' => $app[ 'config' ][ 'database' ] ) );
            // database connection configuret end

            # /*
            $app->mount( '', new Controller\Provider\HomeControllerProvider( ) );

        }

    }
Twitter: @asahina_alice