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

sup*_*bie 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平台上运行,并且需要为每个单独的模块手动创建.

sup*_*ero 17

有四种处理方式:

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

    • AssetManager -后盾assetic -在运行时合并资产,对生产环境和过滤器对CSS/JS缩小和LESS/SASS转换缓存,允许从模块自身的目录暴露的资产.
    • zf2-assetic-module - 由assetic支持- 在运行时处理CSS/JS缩小和LESS/SASS转换
    • BaconAssetLoader - 通过public/在部署时在dir中部署资产来公开模块中的资产


小智 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]
Run Code Online (Sandbox Code Playgroud)

编辑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();
}
Run Code Online (Sandbox Code Playgroud)

用法:/ resource/moduleName/path

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

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