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

时间:2012-04-24 11:25:20

标签: php zend-framework2

某些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

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

也许有一些魔法可以用于httpd.conf或.htaccess?

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

3 个答案:

答案 0 :(得分:17)

有四种处理方法:

  1. 合并public/目录中的资产
  2. 将资产从模块复制粘贴到public/目录
  3. 使用particular Virtual Host Configuration(或通常是网络服务器配置)
  4. 使用资产管理器模块,例如以下之一:

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

答案 1 :(得分:5)

有很多方法可以做到。

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

如上所述,问题是从模块访问/公开。

我的解决方案如下:

编辑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();
}

使用方法: /资源/ MODULENAME /路径

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

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

答案 2 :(得分:0)

您可以尝试使用phing来管理构建过程并让它自动化。你必须编写构建脚本,但之后它就像在CD播放器上播放一样。

当然,测试会很痛苦。