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 模板中输出绝对url
echo $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 复杂条件DEMO
use 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 DEMO
public 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--连接数据库
'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 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 array( 'invokables' => array( 'ConfigHelper' => 'Application\View\Helper\ConfigHelper' ) ));
新建文件:\module\Application\src\Application\View\Helper\ConfigHelper.php '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 array( 'invokables' => array( 'myPlugin' => 'Application\Controller\Plugin\MyPlugin' ) ));
新建文件:\module\Application\src\Application\Controller\Plugin\MyPlugin.php
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()
26.如何解决Fatal error: Call to undefined method Closure::__set_state()错误Bug?
不使用匿名函数,使用service_manager服务管理器!
27.如何使用ZF2 service_manager 服务管理器?
=============================================
新建文件:\config\autoload\cache.global.php array( 'cache_dir' => './data/cache', 'namespace' => 'Filesystem', 'dir_level' => 2, 'filePermission' => 0666, 'dirPermission' => 0755, 'ttl' => 3600, 'clear_stat_cache' => true, 'file_locking' => true ), 'Memcached' => array( 'lifetime' => 3600, 'options' => array( 'servers' => array( array('127.0.0.1', 11211) ), 'namespace' => 'Memcached', 'liboptions' => array( 'COMPRESSION' => true, 'binary_protocol' => true, 'no_block' => true, 'connect_timeout' => 100 ) ) ), 'service_manager' => array( 'factories' => array( 'Zend\Cache\Storage\Adapter\Filesystem' => 'Application\Service\FilesystemCacheService', 'Zend\Cache\Storage\Adapter\Memcached' => 'Application\Service\MemcachedCacheService' ) ));
新建文件:\module\Application\src\Application\Service\FilesystemCacheService.php 'filesystem', 'plugins' => array( 'exception_handler' => array( 'throw_exceptions' => false ), 'serializer' ) )); $config = $sm->get('config'); $cache->setOptions($config['Filesystem']); return $cache; }}
新建文件:\module\Application\src\Application\Service\MemcachedCacheService.php get('config'); $cache = \Zend\Cache\StorageFactory::factory(array( 'adapter' => array( 'name' => 'memcached', 'lifetime' => $config['Memcached']['lifetime'], 'options' => $config['Memcached']['options'] ), 'plugins' => array( 'exception_handler' => array( 'throw_exceptions' => false ) ) )); return $cache; }}
这时,清空你的配置文件缓存,Controller、Plugin里直接使用缓存的方法:
$key = 'yourKey...';$cache = $this->controller->getServiceLocator()->get('Zend\Cache\Storage\Adapter\Filesystem');//$cache = $this->controller->getServiceLocator()->get('Zend\Cache\Storage\Adapter\Memcached');//Memcached$cacheResults = $cache->getItem($key, $success); if($success == true){return unserialize($cacheResults);}else{$cache->setItem($key, serialize('保存你的结果数据到你的缓存...'));}
28.zend framework 2 分页功能如何实现Paginator教程DEMO?
新建文件:\config\autoload\controller_plugins.global.php array( 'invokables' => array( 'PaginatorPlugin' => 'Application\Controller\Plugin\PaginatorPlugin' ) ));
新建文件:\module\Application\src\Application\Controller\Plugin\PaginatorPlugin.php controller->getServiceLocator()->get('Zend\Db\Adapter\Adapter')); $select = $sql->select($table); $select->columns($columns); $paginatorAdapter = new DbSelect($select, $sql); $paginator = new Paginator($paginatorAdapter); return $paginator; }}
Controller中直接使用:$paginator = $this->PaginatorPlugin()->getResults('你的表的名称');$paginator->setCurrentPageNumber((int)$this->params()->fromQuery('p', 1));$paginator->setItemCountPerPage(10); return new ViewModel(array('paginator' => $paginator));
Controller 的 Action 对应的模板:
paginator as $value){foreach ($value as $k => $v) {//输出数据库中的内容var_dump($k);echo '
';var_dump($v);}}?> paginationControl($this->paginator, 'sliding', 'page/global.phtml', array('route' => 'application'));//分页列表?>
新建文件:\module\Application\view\page\global.phtml pageCount): ?>
29.zend framework 2 如何在视图助手ViewHelper中执行插件Controller Plugin?
首先你要知道ViewHelper和Controller Plugin,这里就不再赘述!
\module\Application\src\Application\View\Helper\ConfigHelper.php getServiceLocator()->getServiceLocator()->get('ControllerPluginManager')->get('插件的class名称')->插件方法名(); }}
模板中 直接使用视图助手:
ConfigHelper()->getPath();?>
tips:与上同理,举一反三,如何在插件中使用ServiceManager服务管理器调用其它插件或者其它视图助手,也是一样的原理!
30.zend framework 2 如何在ACTION中优雅的输出Module名称、Controller名称、Action名称 ?
这里 我们采取插件的方式来实现zend framework 2 的ACTION输出Module名称、Controller名称、Action名称
首先你要知道如何Controller Plugin,这里就不再赘述!
\module\Application\src\Application\Controller\Plugin\MyPlugin.php controller->params('controller')) . '/' . $this->controller->params('action')); switch ($type) { case 'm'://module return strtolower($path[0]); break; case 'c'://controller return strtolower($path[1]); break; case 'a'://action return strtolower($path[2]); break; case 'mc'://module/controller return strtolower($path[0].'/'.$path[1]); break; default: return strtolower(join('/', $path));//all break; } return $path; }}
Controller的indexAction中直接输出Module名称、Controller名称、Action名称即可!
var_dump($this->MyPlugin()->getPath());