doure5236
2016-09-18 07:35
采纳率: 0%
浏览 95
已采纳

使用命名空间时找不到php教程类

I got stuck following the doctrine getting started.

Let me show you the code first.

/bootstrap.php

namespace MyApp;

require 'vendor/autoload.php';

require 'config/slim.php'; //Some config files it doesn't matter
require 'config/dependencies.php'; //Some config files it doesn't matter

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Setup;

$doctrineDbConfig = array(
    'driver' => 'pdo_mysql',
    'user' => $config['db']['user'],
    'password' => $config['db']['pass'],
    'dbname' => $config['db']['dbname'],
);

$entityManager = EntityManager::create(
    $doctrineDbConfig,
    Setup::createYAMLMetadataConfiguration(
        array(
            __DIR__ . "/config"
        ),
        $isDevMode = true
    )
);

/cli-config.php

require "bootstrap.php";
return \Doctrine\ORM\Tools\Console\ConsoleRunner::createHelperSet($entityManager);

As you see I am telling doctrine "my entity config file is under /config dir", this is the config file for the product entity:

/config/Product.dcm.yml

Product:
  type: entity
  table: products
  id:
    id:
      type: integer
      generator:
        strategy: AUTO
  fields:
    name:
      type: string

So I run this command:

$ vendor/bin/doctrine orm:schema-tool:update --force --dump-sql

And I got this:

[Doctrine\Common\Persistence\Mapping\MappingException]  
Class 'Product' does not exist         

Let me show you the "Product" class:

/src/Entities/Product.php

namespace MyApp; //If I delete this line, It works

class Product
{
    protected $id;
    protected $name;

    public function getId()
    {
        return $this->id;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }
}

Of course I am using composer autoloader as you see in the bootstrap.php file:

/composer.json

"autoload": {
    "psr-4": {
        "MyApp\\": ["src/", "src/Entities/"]
    }
}

I am mapping the namespace "MyApp". This is working fine when I request the app through the index.php, but it is not working when using the command line.

If I delete the namespace line in the Product.php class, then It works and doctrine finds the class.

I have already tryed using this mapping :

/composer.json

"autoload": {
    "psr-4": {
        "": ["src/", "src/Entities/"]
    }
}

And I have already tryed creating a namespace alias, after reading this answer

Could you please give some advice on this?

Thank you.

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

相关推荐 更多相似问题