如何合并 Zend Framework 2 模块公共目录


How to merge Zend Framework 2 module public directories

一些 zf2 模块有用于分发资源的公共目录,例如 js/css/images。使这些资源可供应用程序使用的最佳做法是什么?

我希望这些资源可以通过http://mysite.com/[moduleName]/自动获得。例如

root/public/js/sitescript.js --> http:''mysite.com'js'sitescript.js

root/module/mymodule/public/js/modulescript.js --> http:''mysite.com'mymodule'js'modulescript.js

root/vendor/vendormodule/public/js/vendorscript.js --> http:''mysite.com'vendormodule'js'vendorscript.js

是否应将这些资源复制到根目录/公共目录?手动复制会很痛苦,我怀疑合并目录的自动构建过程也会非常实用。

也许有一些魔力可以用httpd.conf或.htaccess使用?

也许符号链接是解决方案?但是,符号链接在Windows平台上并不直接,需要为每个单独的模块手动创建。

有 4 种方法可以解决这个问题:

  1. 符号链接public/目录中的资产
  2. 将资源从模块复制粘贴到public/目录
  3. 使用特定的虚拟主机配置(或一般的 Web 服务器配置)
  4. 使用资产管理器模块,例如以下模块之一:

    • AssetManager - 由assetic支持 - 在运行时合并资产,具有用于生产环境的缓存和用于CSS/JS缩小和LESS/SASS转换的过滤器,允许从模块本身的目录中公开资产。
    • zf2-assetic-module - 由assetic支持 - 在运行时处理CSS/JS缩小和LESS/SASS转换
    • BaconAssetLoader - 通过在部署时将模块中的资产部署到public/目录中来公开模块中的资产

有很多方法可以做到这一点。

在我看来,Assetic浪费了计算性能,非常适合这个简单的问题。

如前所述,问题是从模块访问/public。

我的解决方案如下:

编辑 htdocs/yoursite/public/.htaccess 以在 RewriteEngine On 之后立即添加此行:

RewriteRule ^resource/([a-zA-Z0-9'.'-]+)/([a-zA-Z0-9'.'-_'/]+)$ index.php?action=resource&module=$1&path=$2 [QSA,L]

编辑 htdocs/yoursite/public/index.php 并在 chdir(dirname(DIR))之后添加此代码;

if (isset($_GET['action']) && $_GET['action'] == "resource") {
    $module = $_GET['module'];
    $path = $_GET['path'];
    if (!ctype_alnum($module))
        die("Module name must consist of only alphanumeric characters");
    $filetype = pathinfo($path, PATHINFO_EXTENSION);
    $mimetypes = array(
        'js' => "text/javascript",
        'css' => "text/css",
        'jpg' => "image/jpeg",
        'jpeg' => "image/jpeg",
        'png' => "image/png"
    );
    if (!isset($mimetypes[$filetype]))
        die(sprintf("Unrecognized file extension '%s'. Supported extensions: %s.", htmlspecialchars($filetype, ENT_QUOTES), implode(", ", array_keys($mimetypes))));
    $currentDir = realpath(".");
    $destination = realpath("module/$module/public/$path");
    if (!$destination)
        die(sprintf("File not found: '%s'!", htmlspecialchars("module/$module/public/$path", ENT_QUOTES)));
    if (substr($destination, 0, strlen($currentDir)) != $currentDir)
            die(sprintf("Access to '%s' is not allowed!", htmlspecialchars($destination, ENT_QUOTES)));
    header(sprintf("Content-type: %s", $mimetypes[$filetype]));
    readfile("module/$module/public/$path", FALSE);
    die();
}

用法:/资源/模块名称/路径

例:http://yoursite.com/resource/Statistics/css/style.css 将从yoursite/module/Statistics/public/css/style.css读取实际的css。

它快速、安全,不需要您在配置中指定任何路径,不需要安装,不依赖第三方维护,并且不需要查看帮助程序。只需从任何地方访问/资源!享受:)

您可以尝试使用Phing来管理构建过程,并使其自动化所有操作。您必须编写构建脚本,但之后就像在 CD 播放器上播放一样。

当然,对于测试来说,这将是一种痛苦。