Yaf 整合Zend Framework DB ORM
yaf沒有自己的ORM,可以整合zend的db 或者是symfony2的doctrine2 或者是laravel的Eloquent,都是比較強大的ORMP
首先我們整合zendframework1的DB類,以後我們會講解如何繼承zf2的DbAdapter ,ServiceManager或者Cache,以及Doctrine2,Eloquent
一:下載zf1的DB模組目錄結構 YAF\library\Zend,文章底部
二:定義設定檔application.ini
[product]
;layout
application.directory = APP_PATH
application.bootstrap = APP_PATH "Bootstrap.php"
application.library = APP_PATH "../library"
;app
;application.baseUri = ''
;application.dispatcher.defaultModule = index
application.dispatcher.defaultController = index
application.dispatcher.defaultAction = index
;errors (see Bootstrap::initErrors)
application.showErrors=1
;enable the error controller
application.dispatcher.catchException=1
;database
database.adapter = pdo_mysql
;database.params.dbname=APP_PATH "/db/application"
database.params.dbname = "yof_dym"
database.params.host = "127.0.0.1"
database.params.username = "root"
database.params.password = "root"
[devel : product]
;errors (see Bootstrap::initErrors)
application.showErroes=1
三:更改Bootstrap開機檔案
<?phpclass Bootstrap extends Yaf_Bootstrap_Abstract{private $_config;/*get a copy of the config*/public function _initBootstrap(){$this->_config = Yaf_Application::app()->getConfig();}/** initIncludePath is only required because zend components have a shit load of* include_once calls everywhere. Other libraries could probably just use* the autoloader (see _initNamespaces below).*/public function _initIncludePath(){set_include_path(get_include_path().PATH_SEPARATOR.$this->_config->application->library);}public function _initErrors(){if ($this->_config->application->showErrors){error_reporting(-1);ini_set('display_errors', 'On');}}public function _initNamespaces(){Yaf_Loader::getInstance()->registerLocalNameSpace(array("Zend"));}public function _initRoutes(){//this does nothing useful but shows the regex router in action...Yaf_Dispatcher::getInstance()->getRouter()->addRoute("paging_example",new Yaf_Route_Regex("#^/index/page/(\d+)#",array('controller'=>"index"),array(1=>"page")));}public function _initLayout(Yaf_Dispatcher $dispatcher){//註冊外掛程式/*layout allows boilerplate HTML to live in /views/layout rather than every script*/$layout = new LayoutPlugin('layout.phtml');/* Store a reference in the registry so values can be set later.* This is a hack to make up for the lack of a getPlugin* method in the dispatcher.*/Yaf_Registry::set('layout',$layout);/*add the plugin to the dispatcher*/$dispatcher->registerPlugin($layout);}public function _initDefaultDbAdapter(){$dbAdapter = new Zend_Db_Adapter_Pdo_Mysql($this->_config->database->params->toArray());$dbAdapter->query("set names 'utf8'");Zend_Db_Table::setDefaultAdapter($dbAdapter);}}
_initIncludePath自動載入zend類檔案
_initNamespaces定義zend的命名空間
四:ORM的CURD方法
CREATE TABLE IF NOT EXISTS `blog` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(50) NOT NULL,`centent` varchar(200) NOT NULL,PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
<?phpclass IndexController extends Yaf_Controller_Abstract { private $_layout; public function init(){$this->_layout = Yaf_Registry::get('layout');}/*** 首頁面*/public function indexAction() { $blog = new BlogModel();/*view*/$entries = $blog->fetchAll(); print_r($entries);$this->_view->entries = $entries;$this->_view->rowsNum = count($entries)+1; /*layout*/$this->_layout->meta_title = 'blog';}/*** 增加*/public function addAction(){if ($_POST){$bind = array('name'=>$_POST['msg_name'],'content'=>$_POST['msg_content']);$blog = new BlogModel();$result = $blog->add($bind);if ($result){$this->_view->msg = "增加成功";}else{$this->_view->msg = "增加失敗";}}}/*** 編輯*/public function editAction() {if ($_POST){$bind = array('id' => $_POST['msg_id'],'name' => $_POST['msg_name'],'content' => $_POST['msg_centent']);$blog = new BlogModel();$result = $blog->edit($bind, $bind['id']);if ($result){$this->_view->msg = "修改成功";}else{$this->_view->msg = "修改失敗";}}else {$blog = new BlogModel();$id = $this->getRequest()->getParam('id');$msgOne = $blog->getMsgByid($id);$this->_view->msgOne = $msgOne;}}/*** 刪除*/public function deleAction(){$blog = new BlogModel();$id = $this->getRequest()->getParam('id');$result = $blog->delete("`id` = '$id'");if ($result){echo "刪除成功";}else{echo "刪除失敗";}exit();}}
php架構 Yaf整合zendframework2
php架構 Yaf整合zendframework2, zf2的orm 可以作為獨立模組用到yaf中,而且zf2 composer service manger cacheStorage 都可以整合到yaf中。
一:public\index.php 加入composer
chdir(dirname(__DIR__)); // Decline static file requests back to the PHP built-in webserverif (php_sapi_name() === 'cli-server' && is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) {return false;} // Setup autoloadingrequire 'init_autoloader.php'; // Define path to application directorydefine("APP_PATH", dirname(__DIR__)); // Create application, bootstrap, and run$app = new Yaf_Application(APP_PATH . "/conf/application.ini");$app->bootstrap()->run();
根目錄 存放 init_autoloader.php
二:匯入ZF2 模組組件
vendor\ZF2 http://pan.baidu.com/s/1dDfL5RF
三:更改bootstrap設定檔
<?php use Zend\ServiceManager\ServiceManager;use Zend\Mvc\Service\ServiceManagerConfig;use Zend\ModuleManager\Listener\ConfigListener;use Zend\ModuleManager\Listener\ListenerOptions;use Zend\ModuleManager\ModuleEvent; class Bootstrap extends Yaf_Bootstrap_Abstract { public function _initConfig() {$config = Yaf_Application::app()->getConfig();Yaf_Registry::set("config", $config);} public function _initServiceManager() {$configuration = require APP_PATH . '/conf/application.config.php';$smConfig = isset($configuration['service_manager']) ? $configuration['service_manager'] : array();$serviceManager = new ServiceManager(new ServiceManagerConfig($smConfig));$serviceManager->setService('ApplicationConfig', $configuration); $configListener = new ConfigListener(new ListenerOptions($configuration['module_listener_options'])); // If not found cache, merge configif (!$configListener->getMergedConfig(false)) $configListener->onMergeConfig(new ModuleEvent); // If enabled, update the config cacheif ($configListener->getOptions()->getConfigCacheEnabled() &&!file_exists($configListener->getOptions()->getConfigCacheFile())) {//echo "debug";$configFile = $configListener->getOptions()->getConfigCacheFile();$content = "<?php\nreturn " . var_export($configListener->getMergedConfig(false), 1) . ';';file_put_contents($configFile, $content);} $serviceManager->setService('config', $configListener->getMergedConfig(false)); Yaf_Registry::set('ServiceManager', $serviceManager);} public function _initSessionManager() {Yaf_Registry::get('ServiceManager')->get('Zend\Session\SessionManager');} public function _initPlugin(Yaf_Dispatcher $dispatcher) {$user = new UserPlugin();$dispatcher->registerPlugin($user);} }
四:mvc測試
<?php use Zend\Session\Container as SessionContainer;use Zend\Db\TableGateway\TableGateway; class IndexController extends Yaf_Controller_Abstract { public function indexAction() { $adapter = $this->getDbAdapter(); $table = new TableGateway('zt_user', $adapter); $entities = $table->select();foreach ($entities as $entity) {var_dump($entity->username);} $cache = $this->getStorage();$cache->setItem('cache', 'cachedata'); echo $cache->getItem('cache');$this->getLogger()->alert('log'); $this->getView()->assign("content", "Hello World");} /*** db adapter* @return \Zend\Db\Adapter\Adapter*/public function getDbAdapter() {return Yaf_Registry::get('ServiceManager')->get('Zend\Db\Adapter\Adapter');} /*** storage* @return \Zend\Cache\Storage\StorageInterface*/protected function getStorage() {return Yaf_Registry::get('ServiceManager')->get('Zend\Cache\Storage\StorageInterface');} /*** logger* @return \Zend\Log\Zend\Log\Logger*/protected function getLogger() {return Yaf_Registry::get('ServiceManager')->get('Zend\Log\Logger');} }
這樣你訪問public下的index.php 會輸出hello word字樣