Yaf 集成Zend Framework DB ORM
yaf没有自己的ORM,可以集成zend的db 或者是symfony2的doctrine2 或者是laravel的Eloquent,都是比较强大的ORMP
首先我们集成zendframework1的DB类,以后我们会讲解如何继承zf2的DbAdapter ,ServiceManager或者Cache,以及Doctrine2,Eloquent
一:下载zf1的DB模块目录结构 YAFlibraryZend,文章底部
二:定义配置文件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启动文件
_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 ;
_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中。
一:publicindex.php 加入composer
chdir(dirname(__DIR__)); // Decline static file requests back to the PHP built-in webserver if (php_sapi_name() === 'cli-server' && is_file(__DIR__ . parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH))) { return false; } // Setup autoloading require 'init_autoloader.php'; // Define path to application directory define("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 模块组件
vendorZF2 http://pan.baidu.com/s/1dDfL5RF
三:更改bootstrap配置文件
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 config if (!$configListener->getMergedConfig(false)) $configListener->onMergeConfig(new ModuleEvent); // If enabled, update the config cache if ($configListener->getOptions()->getConfigCacheEnabled() && !file_exists($configListener->getOptions()->getConfigCacheFile())) { //echo "debug"; $configFile = $configListener->getOptions()->getConfigCacheFile(); $content = "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('ZendSessionSessionManager'); } public function _initPlugin(Yaf_Dispatcher $dispatcher) { $user = new UserPlugin(); $dispatcher->registerPlugin($user); } }
四:mvc测试
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 ZendDbAdapterAdapter */ public function getDbAdapter() { return Yaf_Registry::get('ServiceManager')->get('ZendDbAdapterAdapter'); } /** * storage * @return ZendCacheStorageStorageInterface */ protected function getStorage() { return Yaf_Registry::get('ServiceManager')->get('ZendCacheStorageStorageInterface'); } /** * logger * @return ZendLogZendLogLogger */ protected function getLogger() { return Yaf_Registry::get('ServiceManager')->get('ZendLogLogger'); } }
这样你访问public下的index.php 会输出hello word字样