Я пытаюсь реализовать FOSRestBundle, поэтому я только что создал свой первый контроллер класса.
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\FOSRestController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use FOS\RestBundle\View\View;
use App\Entity\Product;
class ProductController extends FOSRestController
{
/**
* @Rest\Get("/product")
*/
public function getAction()
{
$em = $this->getDoctrine()->getManager();
$restresult = $em->getRepository('AppBundle:Product')->getAllProduct();
if ($restresult === null) {
return new View("there are no products exist", Response::HTTP_NOT_FOUND);
}
return $restresult;
} // "Get products" [GET] /product*/
}
Но сервер Symfony дал мне эту ошибку: - «Псевдоним пространства имен неизвестной сущности 'AppBundle'». - «Доктрина \ ORM \ ORMException»;
Мой composer.json:
{
"name": "symfony/framework-standard-edition",
"license": "MIT",
"type": "project",
"description": "The \"Symfony Standard Edition\" distribution",
"autoload": {
"psr-4": {
"AppBundle\\": "src/AppBundle"
},
"psr-0": {"": "src/"},
"classmap": [ "app/AppKernel.php", "app/AppCache.php" ]
},
"autoload-dev": {
"psr-4": { "Tests\\": "tests/" },
"files": [ "vendor/symfony/symfony/src/Symfony/Component/VarDumper/Resources/functions/dump.php" ]
},
"require": {
"php": ">=5.5.9",
"doctrine/doctrine-bundle": "^1.6",
"doctrine/orm": "^2.5",
"friendsofsymfony/rest-bundle": "^2.3",
"incenteev/composer-parameter-handler": "^2.0",
"jms/serializer-bundle": "^2.4",
"nelmio/cors-bundle": "^1.5",
"sensio/distribution-bundle": "^5.0.19",
"sensio/framework-extra-bundle": "^5.0.0",
"symfony/monolog-bundle": "^3.1.0",
"symfony/polyfill-apcu": "^1.0",
"symfony/swiftmailer-bundle": "^2.6.4",
"symfony/symfony": "3.4.*",
"twig/twig": "^1.0||^2.0",
"symfony/orm-pack": "^1.0"
},
"require-dev": {
"sensio/generator-bundle": "^3.0",
"symfony/phpunit-bridge": "^4.1"
},
"scripts": {
"symfony-scripts": [
"Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile",
"Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::prepareDeploymentTarget"
],
"post-install-cmd": [
"@symfony-scripts"
],
"post-update-cmd": [
"@symfony-scripts"
]
},
"extra": {
"symfony-app-dir": "app",
"symfony-bin-dir": "bin",
"symfony-var-dir": "var",
"symfony-web-dir": "web",
"symfony-tests-dir": "tests",
"symfony-assets-install": "relative",
"incenteev-parameters": {
"file": "app/config/parameters.yml"
},
"branch-alias": {
"dev-master": "3.4-dev"
}
}
Класс сущности продукта:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Product
*
* @ORM\Table(name = "Product")
* @ORM\Entity
*/
class Product
{
/**
* @var integer
*
* @ORM\Column(name = "idProduct", type = "integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy = "IDENTITY")
*/
private $idproduct;
/**
* @var string
*
* @ORM\Column(name = "productName", type = "string", length=100, nullable=false)
*/
private $productname;
/**
* @var boolean
*
* @ORM\Column(name = "Purchased", type = "boolean", nullable=true)
*/
private $purchased;
/**
* @var \Doctrine\Common\Collections\Collection
*
* @ORM\ManyToMany(targetEntity = "User", mappedBy = "productproduct")
*/
private $useruser;
/**
* Constructor
*/
public function __construct()
{
$this->useruser = new \Doctrine\Common\Collections\ArrayCollection();
}
}
а затем файл ProductRepository:
<?php
namespace AppBundle\Repository;
use Doctrine\ORM\EntityRepository;
class ProductRepository extends EntityRepository
{
public function getAllProduct()
{
$conn = $this->getEntityManager()->getConnection();
$sql = "SELECT * from product";
$stmt = $conn->prepare($sql);
$stmt->execute();
return $stmt->fetchAll();
}
}
Я тоже пытался заменить
$restresult = $em->getRepository('AppBundle:Product')->getAllProduct();
с участием
$restresult = $em->getRepository(Product::class)->getAllProduct();
но теперь ошибка: - «Класс« Приложение \ Сущность \ Продукт »не существует» - «Доктрина \ Common \ Persistence \ Mapping \ MappingException»
Я уже пробовал решения других пользователей stack overlow по этой теме, но ничего. Кто-нибудь может мне помочь?




use App\Entity\Product;
Это должно быть виновником. (в вашем контроллере)
Обновлено: извините, пропустил 1-ю ошибку. Не могли бы вы опубликовать конфигурацию вашей доктрины? Автоматическое отображение включено?
Я заменил его на AppBundle \ Entity \ Product, но ошибка та же
Извините, я увидел 1-ю часть вопроса после того, как разместил, мой плохой. Правильно ли отображается AppBundle?
Да, автоматическое отображение включено. Теперь я нажимаю проект на git, а затем публикую репо здесь
Это мое репо на git
В файле ProductController
вместо
use App\Entity\Product;
замените это на
use AppBundle\Entity\Product;
Ваша структура каталога неверна. https://github.com/axeowl/projectKobe/tree/master/src
Каталоги Entity и Repo должны находиться внутри AppBundle.
Большое спасибо. Оно работает. Моя вина, я тупой. Спасибо и иди Ювентус
очистить кеш