Symfony 4:可以找到文件而不是类

时间:2018-01-02 19:01:36

标签: php symfony

按照文档中的示例:

https://symfony.com/doc/current/page_creation.html

我遇到此错误消息:

  

自动加载器期望类“App \ Controller \ LuckyController”   在文件“/var/www/my-project/vendor/composer/../中定义..   /src/Controller/LuckyController.php“。找到了文件,但是   class不在其中,类名或命名空间可能有拼写错误   在/var/www/my-project/config/services.yaml(已加载   资源“/var/www/my-project/config/services.yaml”)。

在“src / Controller / LuckyController.php”中,我有:

namespace App\Controller;  
use Symfony\Component\HttpFoundation\Response;  
class LuckyController {  
  public function number() {   
    $number = mt_rand(0, 100);  
    return new Response('<html><body>Lucky number: '.$number.'</body></html>');  
  }  
}

在service.yml中,我有:

parameters:

services:
    _defaults:
        autowire: true      
        autoconfigure: true 
        public: false       

    App\:
        resource: '../src/*'
        exclude: '../src/{Entity,Migrations,Tests}'

    App\Controller\:
        resource: '../src/Controller'
        tags: ['controller.service_arguments']

我不确定为什么无法找到“App \ Controller \ LuckyController”类。我想知道是否有人可以帮忙。非常感谢!

2 个答案:

答案 0 :(得分:0)

我添加&#39;&lt;?php&#39;在&#39; LuckyController.php&#39;的顶部,它可以工作。

关于艾伯特的评论,这里是我的作曲家。请注意,当我按照文档中的示例进行操作时,此文件似乎是由&#39; composer require&#39;添加和修改的。到目前为止,我还没有亲自手动编辑它。

{ "type": "project", "license": "proprietary", "require": { "php": "^7.1.3", "ext-iconv": "*", "sensio/framework-extra-bundle": "^5.1", "sensiolabs/security-checker": "^4.1", "symfony/apache-pack": "^1.0", "symfony/console": "^4.0", "symfonby/flex": "^1.0", "symfony/framework-bundle": "^4.0", "symfony/lts": "^4@dev", "symfony/requirements-checker": "^1.0", "symfony/twig-bundle": "^4.0", "symfony/yaml": "^4.0" }, "require-dev": { "symfony/dotenv": "^4.0", "symfony/profiler-pack": "^1.0", "symfony/thanks": "^1.0", "symfony/web-server-bundle": "^4.0" }, "config": { "preferred-install": { "*": "dist" }, "sort-packages": true }, "autoload": { "psr-4": { "App\\": "src/" } }, "autoload-dev": { "psr-4": { "App\\Tests\\": "tests/" } }, "replace": { "symfony/polyfill-iconv": "*", "symfony/polyfill-php71": "*", "symfony/polyfill-php70": "*", "symfony/polyfill-php56": "*" }, "scripts": { "auto-scripts": { "cache:clear": "symfony-cmd", "assets:install --symlink --relative %PUBLIC_DIR%": "symfony-cmd", "requirements-checker": "script", "security-checker security:check": "script" }, "post-install-cmd": [ "@auto-scripts" ], "post-update-cmd": [ "@auto-scripts" ] }, "conflict": { "symfony/symfony": "*" }, "extra": { "symfony": { "id": "...", "allow-contrib": false } } }

答案 1 :(得分:0)

该错误可能是由类定义中的任何语法错误引起的。在以下情况下,我花了半小时对其进行调试:

<?php

namespace App\MyServices;

class MyClass
{
   private $firstAttr;
   private $secondAttr
   private $thirdAttr;

   public function foo($bar)
   {
      // ...
   }
}

您必须在这里发现$secondAttr定义后缺少的分号。如果名称空间和文件名正确,请检查接口,父类和特征是否也是如此。并仔细检查这种语法错误,也可以从特征中“导入”。