如何使用zf2在我的视图辅助函数中获取当前url和基本路径

时间:2016-06-16 07:21:09

标签: php zend-framework2 helper

这个函数是帮手我使用zf2版本2.4我是初学者,请帮助我。 我试过这个:

function getUrlArray(){
     $helperUrl = new Url(); //  use Zend\View\Helper\Url;
     $op =   $helperUrl->url();
     print_r($op); 
}

我收到此错误:

  

致命错误:调用未定义的方法Zend \ View \ Helper \ Url :: url()

1 个答案:

答案 0 :(得分:0)

试试这个ViewHelper:

<?php

namespace YourNamespace\View\Helper\Service;

use YourNamespace\View\Helper\CurrentUri;
use Zend\ServiceManager\FactoryInterface;
use Zend\ServiceManager\ServiceLocatorInterface;

class CurrentUriFactory implements FactoryInterface
{
    /**
     * @param  ServiceLocatorInterface $serviceLocator
     * @return CurrentUri
     */
    public function createService(ServiceLocatorInterface $serviceLocator)
    {
        $helper = new CurrentUri();
        $helper->setRequest($serviceLocator->getServiceLocator()->get('Request'));
        return $helper;
    }
}
<?php

namespace YourNamespace\View\Helper;

use Zend\Stdlib\RequestInterface;
use Zend\View\Helper\AbstractHelper;

/**
 * Helper: $this->currentUri();
 */
class CurrentUri extends AbstractHelper
{
    /**
     * @var \Zend\Http\PhpEnvironment\Request
     */
    protected $request;

    /**
     * @return string
     * @see \Zend\Http\PhpEnvironment\Request
     * @see \Zend\Uri\Uri
     */
    public function __invoke()
    {
        return $this->getRequest()->getUri()->toString();
    }

    /**
     * @return \Zend\Http\PhpEnvironment\Request
     */
    public function getRequest()
    {
        return $this->request;
    }

    /**
     * @param  RequestInterface $request
     * @return CurrentUri
     */
    public function setRequest(RequestInterface $request)
    {
        $this->request = $request;
        return $this;
    }
}