I wanted to build my own __construct for calling my TaskListRepository but it doesn't work:
<?php
namespace App\Controller;
use Doctrine\ORM\Mapping as ORM;
use App\Repository\TaskListRepository;
use Symfony\Component\HttpFoundation\Request;
use FOS\RestBundle\Controller\AbstractFOSRestController;
class ListController extends AbstractFOSRestController
{
/**
* #var string $taskListRepository
*/
private $taskListRepository;
public function __construct(TaskListRepository $taskListRepository)
{
$this->taskListRepository = $taskListRepository;
}
public function getListsAction()
{
return $this->taskListRepository->findAll();
}
}
<?php
namespace App\Repository;
use App\Entity\TaskList;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Symfony\Bridge\Doctrine\RegistryInterface;
/**
* #method TaskList|null find($id, $lockMode = null, $lockVersion = null)
* #method TaskList|null findOneBy(array $criteria, array $orderBy = null)
* #method TaskList[] findAll()
* #method TaskList[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class TaskListRepository extends ServiceEntityRepository
{
public function __construct(RegistryInterface $registry)
{
parent::__construct($registry, TaskList::class);
}
//commented lines removed for readability
}
Error:
Type error: Argument 1 passed to App\Controller\ListController::__construct() must be an instance of
App\Repository\TaskListRepository, none given, called in /data/
applis/GIE/var/cache/dev/ContainerAfvn1yx/getListControllerService.php
on line 14
You should have enabled autowiring for you controllers or configure controller as service explicitly. In your case TaskListRepository should be a service too.
Related
I'm new to Symfony and can't seem to find a way to fix my issue.
I have done an earlier project in which I didn't have this problem but it seems that the method getDoctrine is considered undefined.
enter image description here
here is the 1st route of my controller
<?php
namespace App\Controller;
use Doctrine\Persistence\ObjectManager;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\Persistence\ManagerRegistry;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Form\Extension\HttpFoundation\HttpFoundationExtension;
use Symfony\Component\Form\Forms;
use Symfony\Component\HttpFoundation\Request;
use App\Entity\Accueil;
use App\Entity\Actualite;
use App\Entity\Admin;
use App\Entity\Artistique;
use App\Entity\Avis;
use App\Entity\Equipe;
use App\Entity\Fonction;
use App\Entity\Image;
use App\Entity\Partenaire;
use App\Entity\TypeArtistique;
class SiteValdinguController extends AbstractController
{
/**
* #Route("/", name="app_site_valdingu")
*/
public function index(Request $request, ManagerRegistry $entityManager): Response
{
unset($_POST['triArtNom']);
unset($_POST['triArtNbRepres']);
unset($_POST['triArtTypeArt']);
unset($_POST['triActuNom']);
unset($_POST['triActuDate']);
unset($_POST['triActuTypeArt']);
unset($_POST['triActuTime']);
$repos = $this->getRepository(Accueil::class);
$LesAccueils = $repos->findAll();
$repos = $this->getRepository(Actualite::class);
$LesActualites = $repos->findAll();
$repos = $this->getRepository(Image::class);
$LesImages = $repos->findAll();
return $this->render('site_valdingu/index.html.twig', [
'controller_name' => 'SiteValdinguController',
'LesAccueils'=>$LesAccueils,
'LesActualite'=>$LesActualites
]);
}
Here is the relevant part of my Entity
namespace App\Entity;
use App\Repository\AccueilRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity(repositoryClass: AccueilRepository::class)]
class Accueil
{
#[ORM\Id]
#[ORM\GeneratedValue]
#[ORM\Column]
private ?int $id = null;
#[ORM\Column(length: 255)]
private ?string $Label = null;
#[ORM\Column(length: 255)]
private ?string $Texte = null;
#[ORM\OneToMany(mappedBy: 'Acc_id', targetEntity: Image::class)]
private Collection $img;
`
and here is the relevant part of my Repository
`namespace App\Repository;
use App\Entity\Accueil;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* #extends ServiceEntityRepository<Accueil>
*
* #method Accueil|null find($id, $lockMode = null, $lockVersion = null)
* #method Accueil|null findOneBy(array $criteria, array $orderBy = null)
* #method Accueil[] findAll()
* #method Accueil[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class AccueilRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Accueil::class);
}
public function save(Accueil $entity, bool $flush = false): void
{
$this->getEntityManager()->persist($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
public function remove(Accueil $entity, bool $flush = false): void
{
$this->getEntityManager()->remove($entity);
if ($flush) {
$this->getEntityManager()->flush();
}
}
I used Symfony 6 for my last project, and I thought about not having done the right translation in some places but I didn't notice anything myself.
I also have weird things like no automatic annotations.yaml file created so maybe some routing stuff is messing up but I didn't have do worry about it last time so it feels weird + it seems that it's not the annotations routes that cause the problem since I'm technically on the right page, it just doesn't work and can't extract data from the db.
Both when I use the old getDoctrine()->getRepository() method with the EntityManagerInterface and the immediate getRepository() method with the ManagerRegistry give me the same result
The migrations work so it's not a connexion to db problem.
You are calling $this->getRepository(), so it's trying to use a method that does not exist in SiteValdinguController. What you are trying to achieve is getting each repository using the entity manager. So you need to call $managerRegistry->getRepository() instead.
The correct code would be:
/**
* #Route("/", name="app_site_valdingu")
*/
public function index(Request $request, ManagerRegistry $entityManager): Response
{
unset($_POST['triArtNom']);
unset($_POST['triArtNbRepres']);
unset($_POST['triArtTypeArt']);
unset($_POST['triActuNom']);
unset($_POST['triActuDate']);
unset($_POST['triActuTypeArt']);
unset($_POST['triActuTime']);
$repos = $entityManager->getRepository(Accueil::class);
$LesAccueils = $repos->findAll();
$repos = $entityManager->getRepository(Actualite::class);
$LesActualites = $repos->findAll();
$repos = $entityManager->getRepository(Image::class);
$LesImages = $repos->findAll();
return $this->render('site_valdingu/index.html.twig', [
'controller_name' => 'SiteValdinguController',
'LesAccueils'=>$LesAccueils,
'LesActualite'=>$LesActualites
]);
}
This question already has an answer here:
Class does not exist in getRepository doctrine
(1 answer)
Closed 1 year ago.
I created a new symfony project with an entity Company and a contoller CompanyController. I want to get the results from a database but I keep getting this error: The class 'App\Repository\CompanyRepository' was not found in the chain configured namespaces App\Entity and I don't know why.
I searched the internet but I read only answers that are solving errors when the namespace is not App\Entity. Please help me.
The files are all stored in the src folder as it is when creating a new symfony project. I didn't change any configuration files so every configuration is on default.
Here is my entity:
<?php
namespace App\Entity;
use App\Repository\CompanyRepository;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity(repositoryClass=CompanyRepository::class)
*/
class Company
After that there are just getter and setter.
Here is my controller:
<?php
namespace App\Controller;
use App\Repository\CompanyRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
#[Route('/api/company', name: 'company')]
class CompanyController extends AbstractController
{
#[Route(name: 'company.get', methods: ["GET"])]
public function getCompanies(): Response
{
$entityManager = $this->getDoctrine()->getManager();
$repository = $entityManager->getRepository(CompanyRepository::class);
$companies = $repository->findAll();
$data = [];
foreach ($companies as $company) {
$data[] = $company->toArray();
}
return $this->json([
'data' => $data
]);
}
}
Here is my Company Repository:
<?php
namespace App\Repository;
use App\Entity\Company;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
/**
* #method Company|null find($id, $lockMode = null, $lockVersion = null)
* #method Company|null findOneBy(array $criteria, array $orderBy = null)
* #method Company[] findAll()
* #method Company[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class CompanyRepository extends ServiceEntityRepository
{
public function __construct(ManagerRegistry $registry)
{
parent::__construct($registry, Company::class);
}
// /**
// * #return Company[] Returns an array of Company objects
// */
/*
public function findByExampleField($value)
{
return $this->createQueryBuilder('c')
->andWhere('c.exampleField = :val')
->setParameter('val', $value)
->orderBy('c.id', 'ASC')
->setMaxResults(10)
->getQuery()
->getResult()
;
}
*/
/*
public function findOneBySomeField($value): ?Company
{
return $this->createQueryBuilder('c')
->andWhere('c.exampleField = :val')
->setParameter('val', $value)
->getQuery()
->getOneOrNullResult()
;
}
*/
}
In the controller, replace $repository = $entityManager->getRepository(CompanyRepository::class); with
$repository = $entityManager->getRepository(Company::class);
And replace use App\Repository\CompanyRepository; with use App\Entity\Company;
Because getRepository() expects the Entity class, instead of the Repository class.
<?php
namespace App\Controller;
use App\Entity\Company;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
#[Route('/api/company', name: 'company')]
class CompanyController extends AbstractController
{
#[Route(name: 'company.get', methods: ["GET"])]
public function getCompanies(): Response
{
$entityManager = $this->getDoctrine()->getManager();
$repository = $entityManager->getRepository(Company::class);
$companies = $repository->findAll();
$data = [];
foreach ($companies as $company) {
$data[] = $company->toArray();
}
return $this->json([
'data' => $data
]);
}
}
Here is the error message :
Argument 1 passed to App\Controller\PublisherController::index() must be an instance of Symfony\Component\Mercure\Publisher, instance of Symfony\Component\Mercure\Debug\TraceablePublisher given, called in /home/gw01/Etna/PLI/vendor/symfony/http-kernel/HttpKernel.php on line 145 (500 Internal Server Error)
PublisherController :
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mercure\Publisher;
use Symfony\Component\Mercure\Update;
use Symfony\Component\Routing\Annotation\Route;
/**
* Class PublisherController
* #package App\Controller
*/
class PublisherController extends AbstractController
{
/**
* #Route("/publish/{topic}", name="publisher", methods={"POST"})
*/
public function index(Publisher $publisher, $topic, Request $request)
{
$publisher(new Update($topic, $request->getContent()));
return new Response('success');
}
}
How can i fix this ?
I want to make some operations before controller load and I have problem with include interfaces or classes into function.
My question is how should I do it to start working?
There is a code:
~/src/Controller/ControllerListener.php
<?php
namespace App\EventListener;
use App\Controller\DailyWinController;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
class ControllerListener implements DailyWinController
{
public function onKernelController(FilterControllerEvent $event, LoggerInterface $logger) {
$logger->alert('Working');
}
}
~/src/Controller/DailyWinController.php
<?php
namespace App\Controller;
interface DailyWinController {
// maybe there something?
}
~/src/Controller/UserController.php
<?php
namespace App\Controller;
use App\Entity\User;
use App\Entity\DailyWin;
use Psr\Log\LoggerInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
class UserController extends Controller implements DailyWinController
{
/**
* #Route("/user", name="user")
* #param AuthorizationCheckerInterface $authChecker
* #param UserInterface $user
* #return \Symfony\Component\HttpFoundation\RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function user(AuthorizationCheckerInterface $authChecker, UserInterface $user = null, LoggerInterface $logger) {
if ($authChecker->isGranted('ROLE_USER') === false) {
return $this->redirectToRoute('logowanie');
}
$logger->warning('Logger is working');
$em = $this->getDoctrine()->getManager();
$DWrep = $em->getRepository(DailyWin::class);
$userId = $user->getId();
$dailyWin = $DWrep->findOneBy(['userId' => $userId]);
return $this->render('andprize/user/index.html.twig', array(
'dailyWin' => $dailyWin,
'userId' => $userId
));
}
}
I have the following problem:
FatalThrowableError Type error: Argument 2 passed to
App\EventListener\ControllerListener::onKernelController() must
implement interface Psr\Log\LoggerInterface, string given
You have to inject the logger to the listener.
<?php
namespace App\EventListener;
use App\Controller\DailyWinController;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
class ControllerListener implements DailyWinController
{
protected $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger=$logger;
}
public function onKernelController(FilterControllerEvent $event) {
$this->logger->alert('Working');
}
}
I am implementing a repository pattern in Laravel, and it seems to be very tedious. For example, let's say I have products then I have to create a ProductRepository interface then a ProductRepository class that implements that interface, now I have some very generic methods on the ProductRepository like:
retrieveAll
store
update
delete
And now I have to do the same thing for ingredients. It would be nice if I could simply create a ModelRepository interface with all those generic methods and implement it by passing a generic data type (namely the model), something similar to Java Generics:
<?php
interface ModelRepositoryInterface<T> {
function retrieveAll(): Collection<T>;
function store(T $item);
function update(int $id, T $data);
function delete(int $id);
}
But since php doesn't support generics how can I achieve this simplicity?
You can create a RepositoryServiceProvider to bind your repository interfaces to actual classes.
You can create a abstract Repository class with retrieveAll, store, update, delete and extend your Repositories and implement the interface. I have included below example with magic functions to be able to eloquent methods if I don't have any customization.
The below is not tested but its just to get the idea.
<?php
namespace App\Repositories;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
abstract class AbstractRepository implements RepositoryInterface
{
/**
* #var Builder|Model
*/
protected $model;
/**
* #return mixed
*/
public function getModel()
{
return $this->model;
}
/**
* #param array $columns
* #return \Illuminate\Database\Eloquent\Collection|Model[]
*/
public function all($columns = ['*'])
{
return $this->model->all($columns);
}
/**
* #param $name
* #param $arguments
* #return mixed
*/
public function __call($name, $arguments)
{
return $this->model->{$name}($arguments);
}
}
OrderRepository
<?php
namespace App\Repositories;
use App\Models\Order;
use Illuminate\Support\Facades\Date;
use Illuminate\Support\Facades\DB;
class OrderRepository extends AbstractRepository implements OrderRepositoryInterface
{
/**
* OrderRepository constructor.
* #param Order $model
*/
public function __construct(Order $model)
{
$this->model = $model;
}
public function countPaid(): int
{
return $this->model->paid()->count();
}
/**
* #return int
*/
public function countReady(): int
{
return $this->model->ready()->count();
}
/**
* #return int
*/
public function countCancelled(): int
{
return $this->model->cancelled()->count();
}
}
OrderRepositoryInterface
<?php
namespace App\Repositories;
interface OrderRepositoryInterface
{
}
RepositoryServiceProvider
<?php
namespace App\Providers;
use App\Repositories\OrderRepository;
use App\Repositories\OrderRepositoryInterface;
use Illuminate\Support\ServiceProvider;
class RepositoryServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*
* #return void
*/
public function register()
{
$this->app->bind(OrderRepositoryInterface::class, OrderRepository::class);
}
/**
* Bootstrap any application services.
*
* #return void
*/
public function boot()
{
//
}
}
RepositoryInterface
<?php
namespace App\Repositories;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Collection;
interface RepositoryInterface
{
function retrieveAll(): Collection;
function store(Model $item);
function update(int $id, Model $data);
function delete(int $id);
}