zendframework 3-服务执行两次

时间:2018-10-28 17:28:29

标签: zend-framework3

我创建了个性化服务来确定用户的语言。 我在Moduel.php的Module类内调用服务:

    $languageService = $sm->get("LanguageService");
    $languageService->setLanguage();

该服务的配置可在global.php配置文件以及下面的代码中找到。

'service_manager' => [
        'factories' => [
            \Application\Service\LanguageService::class =>  \Application\Service\Factory\LanguageServiceFactory::class
        ],
        'aliases'=>[
            'LanguageService'=>\Application\Service\LanguageService::class
        ]
    ],

使用xdebug代码的问题被执行两次(构造函数和方法)

我注意到该代码实际上执行了两次。第一次请求的URL是/因此是我的索引。第二个调用是URL /css/bootstrap-select.css.map。我认为这是对插件的内部调用。我认为行为不正确。

1 个答案:

答案 0 :(得分:0)

该行为是正确的。您的服务器有问题。我不知道nginx类型的修复程序,但是对于Apache,使用.htaccess应该添加一些代码,这些代码可以立即提供来自公共目录的文件,而不是通过应用程序。

默认情况下,Zend Skeleton Application.htaccess目录(source)中带有以下public/文件内容:

RewriteEngine On
# The following rule tells Apache that if the requested filename
# exists, simply serve it.
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^.*$ - [L]
# The following rewrites all other queries to index.php. The 
# condition ensures that if you are using Apache aliases to do
# mass virtual hosting or installed the project in a subdirectory,
# the base path will be prepended to allow proper resolution of
# the index.php file; it will work in non-aliased environments
# as well, providing a safe, one-size fits all solution.
RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
RewriteRule ^(.*)$ %{ENV:BASE}/index.php [L]

项目根目录没有随附.htaccess文件。如果您正确映射服务器以将项目public/目录用作项目访问点,则将不需要它。


基于评论讨论,我假设某个配置不正确,并将/css/*请求定向到项目根目录。为了确保这些请求不会进入项目,我在项目根目录中有以下.htaccess

RewriteEngine On

# If URL to the application is http://foo.com/path/to/ZendSkeletonApplication/
# the set the base to /path/to/ZendSkeletonApplication/
RewriteBase /

# Remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

# Below is ZF2 default
RewriteRule ^\.htaccess$ - [F]
RewriteCond %{REQUEST_URI} =""
RewriteRule ^.*$ public/index.php [NC,L]

RewriteCond %{REQUEST_URI} !^/public/.*$
RewriteRule ^(.*)$ public/$1

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^.*$ - [NC,L]

RewriteRule ^public/.*$ public/index.php [NC,L]

不是很漂亮,但是可以完成工作。