• ZF2开发中常用操作


    1.如何在zend framework 2 Controller获取网址?

    use ZendViewHelperServerUrl;
    //http://my.oschina.net/cart/
    $url = new ServerUrl();
    var_dump($url->__invoke());

    使用session

    $session = new Session('namespace','name');
    $session->write(['a'=>1,'b'=>2]);
    $a = $session->read();

    2.如何在zend framework 2 Controller获取adapter?

    $adapterOrSqlObject = $this->getServiceLocator ()->get ( 'ZendDbAdapterAdapter' );

    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
    
    $request->getQuery('t')->toArray();//get(array)
    $request->getPost('t')->toArray();//post(array)

    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 ZendDbSqlPredicatePredicate;
    
    $predicate = new Predicate();
    $predicate->in('字段名', array('1', '2'));
    $select->where(array($predicate));
    	public function fetchAll() {
    		$sql = new Sql ( $this->getServiceLocator ()->get ( 'ZendDbAdapterAdapter' ));
    	
    		$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',
    		), endDbSqlSelect::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' 
    		), endDbSqlSelect::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(
    			'ZendDbAdapterAdapter' => function ($sm) use ($dbParams) {
    				return new ZendDbAdapterAdapter(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 报错信息?


    moduleApplicationconfigmodule.config.php
    
     'view_manager' => array(
            'display_not_found_reason' => true,//false关闭错误提示
            'display_exceptions'       => true,//false关闭错误提示
        ),


    19.zend framework 2 加载modules、config配置文件太多,如何提高性能速度?

    configapplication.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 ZendServiceManagerConfig.
       // '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么?

    新建文件:
    
    configautoloadview_helpers.global.php
    
    <?php
    return array(
        'view_helpers' => array(
            'invokables' => array(
                'ConfigHelper' => 'ApplicationViewHelperConfigHelper'
            )
        )
    );



    新建文件:
    
    moduleApplicationsrcApplicationViewHelperConfigHelper.php
    
    <?php
    namespace ApplicationViewHelper;
    
    use ZendViewHelperAbstractHelper;
    
    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?


    新建文件:
    
    configautoloadcontroller_plugins.global.php
    
    <?php
    return array(
        'controller_plugins' => array(
            'invokables' => array(
                'myPlugin' => 'ApplicationControllerPluginMyPlugin'
            )
        )
    );


    新建文件:
    
    moduleApplicationsrcApplicationControllerPluginMyPlugin.php
    
    <?php
    namespace ApplicationControllerPlugin;
    
    use ZendMvcControllerPluginAbstractPlugin;
    
    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配置文件缓存文件,


    datacachemodule-classmap-cache.key.php
    
    datacachemodule-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 服务管理器?

    =============================================

    新建文件:
    
    configautoloadcache.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(
                'ZendCacheStorageAdapterFilesystem' => 'ApplicationServiceFilesystemCacheService',
                'ZendCacheStorageAdapterMemcached' => 'ApplicationServiceMemcachedCacheService'
            )
        )
    );
    


    新建文件:
    
    moduleApplicationsrcApplicationServiceFilesystemCacheService.php
    
    <?php
    namespace ApplicationService;
    
    use ZendServiceManagerFactoryInterface;
    use ZendServiceManagerServiceLocatorInterface;
    
    class FilesystemCacheService implements FactoryInterface
    {
    
        public function createService(ServiceLocatorInterface $sm)
        {
            $cache = endCacheStorageFactory::factory(array(
                'adapter' => 'filesystem',
                'plugins' => array(
                    'exception_handler' => array(
                        'throw_exceptions' => false
                    ),
                    'serializer'
                )
            ));
            $config = $sm->get('config');
            $cache->setOptions($config['Filesystem']);
            
            return $cache;
        }
    }
    


    新建文件:
    
    moduleApplicationsrcApplicationServiceMemcachedCacheService.php
    
    <?php
    namespace ApplicationService;
    
    use ZendServiceManagerFactoryInterface;
    use ZendServiceManagerServiceLocatorInterface;
    
    class MemcachedCacheService implements FactoryInterface
    {
    
        public function createService(ServiceLocatorInterface $sm)
        {
            $config = $sm->get('config');
            $cache = endCacheStorageFactory::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('ZendCacheStorageAdapterFilesystem');
    //$cache = $this->controller->getServiceLocator()->get('ZendCacheStorageAdapterMemcached');//Memcached
    $cacheResults = $cache->getItem($key, $success);
    			
    if($success == true){
    return unserialize($cacheResults);
    }else{
    $cache->setItem($key, serialize('保存你的结果数据到你的缓存...'));
    }
    


    28.zend framework 2 分页功能如何实现Paginator教程DEMO?


    新建文件:
    
    configautoloadcontroller_plugins.global.php
    
    <?php
    return array(
        'controller_plugins' => array(
            'invokables' => array(
                'PaginatorPlugin' => 'ApplicationControllerPluginPaginatorPlugin'
            )
        )
    );
    新建文件:
    
    moduleApplicationsrcApplicationControllerPluginPaginatorPlugin.php
    
    
    <?php
    namespace ApplicationControllerPlugin;
    
    use ZendMvcControllerPluginAbstractPlugin;
    use ZendPaginatorAdapterDbSelect;
    use ZendPaginatorPaginator;
    use ZendDbSqlSql;
    
    class PaginatorPlugin extends AbstractPlugin {
    	public function getResults($table, array $columns = array('*')) {
    	    
    		$sql = new Sql ($this->controller->getServiceLocator()->get('ZendDbAdapterAdapter'));
    		$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'));//分页列表?>



    新建文件:
    
    moduleApplicationviewpageglobal.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,这里就不再赘述!


    moduleApplicationsrcApplicationViewHelperConfigHelper.php
    
    <?php
    namespace ApplicationViewHelper;
    
    use ZendViewHelperAbstractHelper;
    use ZendServiceManagerServiceLocatorAwareInterface;
    
    class ConfigHelper extends AbstractHelper implements ServiceLocatorAwareInterface
    {
        use endServiceManagerServiceLocatorAwareTrait;
        
        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,这里就不再赘述!



    moduleApplicationsrcApplicationControllerPluginMyPlugin.php
    
    
    <?php
    namespace ApplicationControllerPlugin;
    
    use ZendMvcControllerPluginAbstractPlugin;
    
    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());
  • 相关阅读:
    2.字符设备驱动开发
    1.Linux内核模块编程
    Linux基础知识
    数据结构小结
    3基本概念
    2在HTML中使用JavaScript
    1JavaScript简介
    20161230【作业1】静态网页制作笔记
    14非屏幕媒体
    13用户界面样式
  • 原文地址:https://www.cnblogs.com/wepe/p/7424503.html
Copyright © 2020-2023  润新知