ZF2开发中常用操作 - zend framework 2 开发实战中常用操作最热门30问let 发布于 1年前,共有 3 条评论 1.如何在zend framework 2 Controller获取网址?use Zend\View\Helper\ServerUrl; //http://my.oschina.net/cart/ $url = new ServerUrl(); var_dump($url->__invoke()); 2.如何在zend framework 2 Controller获取adapter?$adapterOrSqlObject = $this->getServiceLocator ()->get ( 'Zend\Db\Adapter\Adapter' ); 3.zend framework 2 数据集如何转换为数组?iterator_to_array($results) 4.如何在zend framework 2 Controller获得路由参数?$format = $this->getEvent()->getRouteMatch()->getParam('format'); $format = $this->params()->fromRoute('format'); 5.如何在zend framework 2 Controller获得GET和POST参数?$request = $this->getRequest(); $request->getQuery('t');//get $request->getPost('t');//post 6.zend framework 2 如何获取上一次的插入ID?$this->adapter->getDriver()->getConnection()->getLastGeneratedValue(); 7.zend framework 2 如何进行跳转?$this->redirect ()->toRoute ( 'AdminHome/AdminController/AdminAction/AdminActionParam', array('controller' => 'seo', 'action' => 'index', 'format' => $resource->resource_id) ); 8.zend framework 2 如何调试SQL语句?echo $sql->getSqlStringForSqlObject($select); exit(); 9.如何在zend framework 2 如何直接执行纯SQL语句?$this->getAdapter()->query('UPDATE `'.$this->documentCountTable.'` SET `'.$action.'` = `'.$action.'` +1 WHERE `document_item_id` =?', array($documentItemId)); 10.如何在zend framework 2 layout获得网站根目录$this->basePath() 11.如何在zend framework 2 模板中安全输出变量$this->escapeHtml() 12.如何在zend framework 2 模板中输出url$this->url('authentication_admin_user', array('action' => 'delete', 'id' => $user->id)); $this->url('AdminHome/AdminController/AdminAction/AdminActionParam', array('controller' => 'seo', 'action' => 'index', 'format' => $resource->resource_id)); 13.如何在zend framework 2 模板中输出绝对urlecho $this->serverUrl().$this->basePath().'/'; 14.如何在zend framework 2 模板输出layout$this->layout('admin/layout/layout');//方法1 $layoutViewModel = $this->layout(); $layoutViewModel->setTemplate('layout/another');//方法2 //bof $headerView = new ViewModel(); $headerView->setTemplate('admin/index/header');//模板 $sidebarView = new ViewModel(); $sidebarView->setTemplate('admin/index/sidebar');//模板 $this->layout('admin/layout/layout');//layout $this->layout()->addChild($headerView, 'header'); $this->layout()->addChild($sidebarView, 'sidebar'); return new ViewModel(); //eof $responseView = new ViewModel(); // $responseView->setTerminal(true); return $responseView; 15.如何在zend framework 2 sql 复杂条件DEMOuse Zend\Db\Sql\Predicate\Predicate; $predicate = new Predicate(); $predicate->in('字段名', array('1', '2')); $select->where(array($predicate)); public function fetchAll() { $sql = new Sql ( $this->getServiceLocator ()->get ( 'Zend\Db\Adapter\Adapter' )); $whereArray = array (); $whereArray ['r.is_seo'] = '1'; $select = $sql->select (); $select->from ( array('s'=>'seo') )->columns ( array ( '为了避免冲突我新命名的字段' => '数据库里面的字段', ) )->join ( array('r'=>'resource'), 's.resource_id = r.resource_id', array ( 'resource', ), \Zend\Db\Sql\Select::JOIN_LEFT )->where ( $whereArray ); $request = $this->getRequest(); if ($request->isPost()) { $predicate = new Predicate(); $predicate->like('r.resource', '%'.$request->getPost('filter_resource').'%'); $select->where(array($predicate)); } //echo $sql->getSqlStringForSqlObject($select); $statement = $sql->prepareStatementForSqlObject($select); $results = $statement->execute(); return $results; } 16.如何在zend framework 2 tableGateway join DEMOpublic function fetchAll() { $sql = new Sql ( $this->tableGateway->getAdapter () ); $whereArray = array (); $whereArray ['resource.is_seo'] = '1'; $select = $sql->select (); $select->from ( 'seo' )->columns ( array ( 'seo_id', 'seo_tilte', 'seo_description' ) )->join ( 'resource', 'seo.resource_id = resource.resource_id', array ( 'resource', 'module' ), \Zend\Db\Sql\Select::JOIN_LEFT )->where ( $whereArray ); $filter_resource = (isset ( $_POST ['filter_resource'] ) and ! empty ( $_POST ['filter_resource'] )) ? $_POST ['filter_resource'] : 0; if ($filter_resource) { $predicate = new Predicate(); $predicate->like('resource.resource', '%'.$filter_resource.'%'); $select->where(array($predicate)); } //echo $sql->getSqlStringForSqlObject($select); $resultSet = $this->tableGateway->selectWith ( $select ); return $resultSet; } 17.如何在zend framework 2 modules--连接数据库<?php $dbParams = array( 'database' => 'dbname', 'username' => 'root', 'password' => '123456', 'hostname' => '127.0.0.1', ); return array( 'service_manager' => array( 'factories' => array( 'Zend\Db\Adapter\Adapter' => function ($sm) use ($dbParams) { return new Zend\Db\Adapter\Adapter(array( 'driver' => 'pdo', 'dsn' => 'mysql:dbname='.$dbParams['database'].';host='.$dbParams['hostname'], 'database' => $dbParams['database'], 'username' => $dbParams['username'], 'password' => $dbParams['password'], 'hostname' => $dbParams['hostname'], )); }, ), ), );
18.如何打开zend framework 2 debug或者关闭zend framework 2 报错信息? \module\Application\config\module.config.php 'view_manager' => array( 'display_not_found_reason' => true,//false关闭错误提示 'display_exceptions' => true,//false关闭错误提示 ), 19.zend framework 2 加载modules、config配置文件太多,如何提高性能速度?\config\application.config.php <?php return array( // This should be an array of module namespaces used in the application. 'modules' => array( 'Application', ), // These are various options for the listeners attached to the ModuleManager 'module_listener_options' => array( // This should be an array of paths in which modules reside. // If a string key is provided, the listener will consider that a module // namespace, the value of that key the specific path to that module's // Module class. 'module_paths' => array( './module', './vendor', ), // An array of paths from which to glob configuration files after // modules are loaded. These effectively override configuration // provided by modules themselves. Paths may use GLOB_BRACE notation. 'config_glob_paths' => array( 'config/autoload/{,*.}{global,local}.php', ), // Whether or not to enable a configuration cache. // If enabled, the merged configuration will be cached and used in // subsequent requests. 'config_cache_enabled' => true, // The key used to create the configuration cache file name. 'config_cache_key' => 'key', // Whether or not to enable a module class map cache. // If enabled, creates a module class map cache which will be used // by in future requests, to reduce the autoloading process. 'module_map_cache_enabled' => true, // The key used to create the class map cache file name. 'module_map_cache_key' => 'key', // The path in which to cache merged configuration. 'cache_dir' => './data/cache', // Whether or not to enable modules dependency checking. // Enabled by default, prevents usage of modules that depend on other modules // that weren't loaded. 'check_dependencies' => true, ), // Used to create an own service manager. May contain one or more child arrays. //'service_listener_options' => array( // array( // 'service_manager' => $stringServiceManagerName, // 'config_key' => $stringConfigKey, // 'interface' => $stringOptionalInterface, // 'method' => $stringRequiredMethodName, // ), // ) // Initial configuration with which to seed the ServiceManager. // Should be compatible with Zend\ServiceManager\Config. // 'service_manager' => array(), ); 20.如何使用zend framework 2 自带的表单操作HTML?21.如何把ZF2库 移动到public外面WEB访问不到的目录,以确保安全?
/init_autoloader.php $zf2Path = false; 替换为你的ZF2库的真实路径,如: $zf2Path = '../../zf-2.3.2/library'; 22.如何让zend framework 2 在访问时,末尾不加斜线/和加斜线/都不报错达到兼容? 'may_terminate' => true, 'child_routes' => array( 'default' => array( 'type' => 'Segment', 'options' => array( 'route' => '/[:controller[/:action]][/]', 'constraints' => array( 'controller' => '[a-zA-Z][a-zA-Z0-9_-]*', 'action' => '[a-zA-Z][a-zA-Z0-9_-]*', ), 'defaults' => array( ), ), ), ), 23.zend framework 2 如何在模板中轻松引入Modules、Controller、View都可以访问的方法,是view_helpers么?新建文件: \config\autoload\view_helpers.global.php <?php return array( 'view_helpers' => array( 'invokables' => array( 'ConfigHelper' => 'Application\View\Helper\ConfigHelper' ) ) ); 新建文件: \module\Application\src\Application\View\Helper\ConfigHelper.php <?php namespace Application\View\Helper; use Zend\View\Helper\AbstractHelper; class ConfigHelper extends AbstractHelper { public $hello = array( 1 => 'http://my.oschina.net/cart/blog/174571', 2 => 'http://my.oschina.net/cart/' ); public function test($key){ return $key; } } 模板中调用: var_dump($this->ConfigHelper()->hello); var_dump($this->ConfigHelper()->test('http://my.oschina.net/cart/')); Modules、Controller中就像 引入常规类文件 class 一样,这里就不再赘述 24.zend framework 2 如何引入我自己写的插件controller_plugins? 新建文件: \config\autoload\controller_plugins.global.php <?php return array( 'controller_plugins' => array( 'invokables' => array( 'myPlugin' => 'Application\Controller\Plugin\MyPlugin' ) ) ); 新建文件: \module\Application\src\Application\Controller\Plugin\MyPlugin.php <?php namespace Application\Controller\Plugin; use Zend\Mvc\Controller\Plugin\AbstractPlugin; class MyPlugin extends AbstractPlugin { public function getResults($key) { return $key; } } Controller中使用: var_dump($this->MyPlugin()->getResults('hello,http://my.oschina.net/cart/')); Moudle中使用: var_dump($serviceLocator->get('ControllerPluginManager'))->get('MyPlugin')->getResults('hello,http://my.oschina.net/cart/'); var_dump($sm->get('ControllerPluginManager'))->get('MyPlugin')->getResults('hello,http://my.oschina.net/cart/'); var_dump($this->controller->getServiceLocator()->get('ControllerPluginManager'))->get('MyPlugin')->getResults('hello,http://my.oschina.net/cart/'); 25.zend framework 2 如何使用文件缓存和内存缓存Memcached、APC等相关问题解答zend framework 2 开启配置文件缓存application.config.php下的 'config_cache_enabled' => true, 'module_map_cache_enabled' => true, 时,这时会生成2个zend framework 2配置文件缓存文件, \data\cache\module-classmap-cache.key.php \data\cache\module-config-cache.key.php同时,如果在zend framework 2的config配置文件使用匿名函数时,这时就会报错(不使用匿名函数或者不开启配置文件缓存都没事,同时使用就报错,ZF2的Bug): Fatal error: Call to undefined method Closure::__set_state() |
|