文档章节

ZF2开发中常用操作 - zend framework 2 开发实战中常用操作最热门30问

letwang
 letwang
发布于 2013/11/06 14:33
字数 2524
阅读 3909
收藏 23

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--连接数据库

<?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?

单击查看ZF2表单操作大全

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,


时,这时会生成2zend 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

<?php
return array(
    'Filesystem' => 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

<?php
namespace Application\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class FilesystemCacheService implements FactoryInterface
{

    public function createService(ServiceLocatorInterface $sm)
    {
        $cache = \Zend\Cache\StorageFactory::factory(array(
            'adapter' => '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

<?php
namespace Application\Service;

use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class MemcachedCacheService implements FactoryInterface
{

    public function createService(ServiceLocatorInterface $sm)
    {
        $config = $sm->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

<?php
return array(
    'controller_plugins' => array(
        'invokables' => array(
            'PaginatorPlugin' => 'Application\Controller\Plugin\PaginatorPlugin'
        )
    )
);
新建文件:

\module\Application\src\Application\Controller\Plugin\PaginatorPlugin.php


<?php
namespace Application\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;
use Zend\Paginator\Adapter\DbSelect;
use Zend\Paginator\Paginator;
use Zend\Db\Sql\Sql;

class PaginatorPlugin extends AbstractPlugin {
	public function getResults($table, array $columns = array('*')) {
	    
		$sql = new Sql ($this->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 对应的模板:

<?php
foreach($this->paginator as $value){
foreach ($value as $k => $v) {//输出数据库中的内容
var_dump($k);
echo '<hr>';
var_dump($v);
}
}
?>


<?php echo $this->paginationControl($this->paginator, 'sliding', 'page/global.phtml', array('route' => 'application'));//分页列表?>



新建文件:

\module\Application\view\page\global.phtml


<?php if ($this->pageCount): ?>
<div class="text-right">
<ul class="pagination">
<?php if (isset($this->previous)): ?>
<li><a href="<?php echo $this->url($this->route); ?>?p=<?php echo $this->previous; ?>"> << </a></li>
<?php else: ?>
<li class="disabled"><a href="javascript:;"> << </a></li>
<?php endif; ?>

<?php foreach ($this->pagesInRange as $page): ?>
   <?php if ($page != $this->current): ?>
<li><a href="<?php echo $this->url($this->route);?>?p=<?php echo $page; ?>"><?php echo $page; ?></a></li>
   <?php else: ?>
<li class="active"><a href="javascript:;"><?php echo $page; ?></a></li>
   <?php endif; ?>
<?php endforeach; ?>

<?php if (isset($this->next)): ?>
<li><a href="<?php echo $this->url($this->route); ?>?p=<?php echo $this->next; ?>"> >> </a></li>
<?php else: ?>
<li class="disabled"><a href="javascript:;"> >> </a></li>
<?php endif; ?>
</ul>
</div>
<?php endif; ?>



29.zend framework 2 如何在视图助手ViewHelper中执行插件Controller Plugin?

首先你要知道创建视图助手ViewHelper和创建插件Controller Plugin,这里就不再赘述!


\module\Application\src\Application\View\Helper\ConfigHelper.php

<?php
namespace Application\View\Helper;

use Zend\View\Helper\AbstractHelper;
use Zend\ServiceManager\ServiceLocatorAwareInterface;

class ConfigHelper extends AbstractHelper implements ServiceLocatorAwareInterface
{
    use \Zend\ServiceManager\ServiceLocatorAwareTrait;
    
    public function getPath(){
        return $this->getServiceLocator()->getServiceLocator()->get('ControllerPluginManager')->get('插件的class名称')->插件方法名();
    }
}

模板中 直接使用视图助手:

<?php echo $this->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


<?php
namespace Application\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;

class MyPlugin extends AbstractPlugin {
    
    public function getPath($type = false){
        $path = explode('/', str_ireplace('\Controller\\', '/', $this->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());





© 著作权归作者所有

共有 人打赏支持
letwang
粉丝 160
博文 55
码字总数 75707
作品 1
南京
技术主管
私信 提问
加载中

评论(4)

比巴卜
41
letwang
letwang

引用来自“小林同志”的评论

实用 非常感谢!希望再来个30
哈哈哈 好东西不是经常有的
小林同志
实用 非常感谢!希望再来个30
如来神掌
如来神掌
整理的不错~ 当初碰到了好多坎坷呀
菜菜鸟Zend Framework 2 不完全学习涂鸦(一)-- 安装配置

声明:本人 PHPer 菜鸟一枚,Zend Framework 2 框架的菜菜鸟,刚学习 ZF2 不过 2 天。由于英语实在太破,所以一开始只能找网上 ZF2 中文教程,但很多教程都只说到 ZF2 安装与配置就结束了,没...

Jacky.Wang
2013/07/18
0
27
《Zend Framework 2 程序员参考指南》 一、概述 Overview

Zend Framework 2是一个使用PHP 5.3+(含以上版本)开发WEB应用程序和服务的开放源代码的框架(framework)。Zend Framework 2使用100%的面相对象代码,并且利用了大部分PHP5.3 的新功能,命...

v8v9v3000
2013/10/03
0
0
Zend Framework 2.0 正式版发布及新功能介绍

著名php开源框架Zend Framework经历了长达数年的开发,终于在2012年9月5日正式发布了2.0版本,下简称ZF2。时隔Zend 1.0版本的发布已经有5年之久。php的框架一直都是百家争鸣的,但是作为php...

今天星期一
2012/09/07
7.7K
24
Zend Framework2 入门教程

由于篇幅过长使用过QQ空间的自动清理功能,不知道是否被删减有内容。 zend framework2 入门教程源码 http://pan.baidu.com/s/1kTuRGn9 目录 序言 5 第 1章 Zend Framework2 简介 6 1.1 Zend...

lai1362000
2014/02/19
23.6K
8
Zend Framework 2.0 (zf2) 进阶数据库操作

连接数据库 首选的操作DB方式还是继承TableGateway,比如现在要操作的数据库为test,数据表为mydbtable,新建一个类如下 class MyDbTable extends ZendDbTableGatewayTableGateway{} 连接数据...

一切_放空
2013/08/27
0
0

没有更多内容

加载失败,请刷新页面

加载更多

使用JavaScript编写iOS应用业务逻辑

JSAUIKitCocoa使你可以使用JavaScript编写对性能要求不高但可能变动性很大的iOS应用的业务逻辑部分,View组件、需要多线程支持的Model等则直接使用原生对象。 编写方式与React Native相似,但...

neal01
8分钟前
0
0
艺术品区块链溯源防伪平台(连载一)

Netkiller Blockchain 手札 作者正在找工作,联系方式 13113668890 Mr. Neo Chan, 陈景峯(BG7NYT) 中国广东省深圳市望海路半岛城邦三期 518067 +86 13113668890 <netkiller@msn.com> 文档始创...

netkiller-
8分钟前
0
0
0032-如何在CDH启用Kerberos的情况下安装及使用Sentry(二)

温馨提示:要看高清无码套图,请使用手机打开并单击图片放大查看。 5.Sentry列权限管理 1.在集群所有节点添加fayson_r用户 [root@ip-172-31-6-148 cdh-shell-bak]# useradd fayson_r[root@i...

Hadoop实操
12分钟前
0
0
Nginx配置中Location的优先级

根据Nginx的官方文档,Location标签一共有四个修饰符,分别是: (1) =:表示完全匹配; (2) ^~:匹配URI的前缀,并且后面的正则表达式不再匹配,如果一个URI同时满足两个规则的话,匹配最长的规...

cloes
昨天
0
0
Xcode 10 Archive 卡死问题

前段时间贪新鲜更新了xcode 10,发现就是自己没事找事后悔啊........ 首先是 libstdc++.6.0.9.tbd 已不被使用,以前的项目是一顿报错!!!一个个改也不是办法还有一些第三方的用到只好把lib...

壹峰
昨天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部