zend-framework - 将 baseurl 值放入我的 Controller

标签 zend-framework zend-controller base-url

我正在创建一个需要

的返回值的操作助手
Zend_View_Helper_BaseUrl

我该怎么做?

最佳答案

$this->view->baseUrl() 应该可以工作。

但我建议创建新的操作助手,它基本上是 View 助手的副本,但您可以根据需要进行修改:

/**
 * Generate URL of the current domain
 *
 */
class My_Controller_Action_Helper_BaseUrl
extends Zend_Controller_Action_Helper_Abstract
{
    public function direct($file = null, $full = true)
    {
        return $this->baseUrl($file, $full);
    }

    /**
     * BaseUrl
     *
     * @var string
     */
    protected $_baseUrl;

    /**
     * Returns site's base url, or file with base url prepended
     *
     * $file is appended to the base url for simplicity
     *
     * @param  string|null $file
     * @return string
     */
    public function baseUrl($file = null)
    {
        // Get baseUrl
        $baseUrl = $this->getBaseUrl();

        // Remove trailing slashes
        if (null !== $file) {
            $file = '/' . ltrim($file, '/\\');
        }

        return $baseUrl . $file;
    }

    /**
     * Set BaseUrl
     *
     * @param  string $base
     * @return My_Controller_Action_Helper_BaseUrl
     */
    public function setBaseUrl($base)
    {
        $this->_baseUrl = rtrim($base, '/\\');
        return $this;
    }

    /**
     * Get BaseUrl
     * @return string
     */
    public function getBaseUrl()
    {
        if ($this->_baseUrl === null) {
            /** @see Zend_Controller_Front */
            require_once 'Zend/Controller/Front.php';
            $baseUrl = Zend_Controller_Front::getInstance()->getBaseUrl();

            // Remove scriptname, eg. index.php from baseUrl
            $baseUrl = $this->_removeScriptName($baseUrl);

            $this->setBaseUrl($baseUrl);
        }

        return $this->_baseUrl;
    }

    /**
     * Remove Script filename from baseurl
     *
     * @param  string $url
     * @return string
     */
    protected function _removeScriptName($url)
    {
        if (!isset($_SERVER['SCRIPT_NAME'])) {
            // We can't do much now can we? (Well, we could parse out by ".")
            return $url;
        }

        if (($pos = strripos($url, basename($_SERVER['SCRIPT_NAME']))) !== false) {
            $url = substr($url, 0, $pos);
        }

        return $url;
    }
}

关于zend-framework - 将 baseurl 值放入我的 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2665705/

相关文章:

zend-framework - Zend Framework - 我如何在 Controller 的一些 Action 之间共享通用代码?

apache - 代码点火器,未找到 404 错误

php - 像来自 codeigniter for opencart 的 base_url 之类的东西?

php - 使用 Zend 框架创建绝对 URL 的最佳实践?

zend-framework - 多重/嵌套 "select where"与 Zend_Db_Select

zend-framework - Zend 框架 : How to set default mail transport in configuration file?

zend-framework - Doctrine2或zend_db

php - Zend Framework MVC 重定向到不同的 Controller 和操作

zend-framework - Zend_Controller_Action _forward 使用(或滥用)案例

php - 确定网站的 'root' 位置