Symfony Route. Can't set annotations - symfony

I can't understand, if i create crud controller with
bin/console make:crud all routes work from controller
like
/**
* #Route("/", name="product_index", methods="GET")
*/
public function index(ProductRepository $productRepository): Response
{
return $this->render('product/index.html.twig', ['products' => $productRepository->findAll()]);
}
.
If i create controller with bin/console make:controller
and define controller with annotation by myself they don't work
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use JMS\Serializer\SerializerBuilder;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Entity\Product;
use App\Repository\ProductRepository;
use JMS\Serializer\SerializationContext;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
class FirstApiController extends AbstractController
{
/**
*
* #Route("/first_api", name="first_api")
*/
public function index(ProductRepository $productRepository)
{
$data = $productRepository->findAll();
$serializer = SerializerBuilder::create()->build();
# $jsonContent = $serializer->serialize($data, 'json');
$jsonContent = $serializer->serialize($data, 'json', SerializationContext::create()->setGroups(array('details')));
$response = JsonResponse::fromJsonString($jsonContent);
return $response;
}
/*
* #Route("/first_api/send", name="send")
*
*/
public function send()
{
$a = "text";
return $a;
}
}
Why that route doesn't work
#Route("/first_api/send", name="send") ?
In routes.yaml i wrote nothing, just empty file.

I used wrong syntax !I used
/* <-- the error is here
* #Route("/first_api/send", name="send")
*
*/
I need to use
/** <-- i nee two "*"
* #Route("/first_api/send", name="send")
*
*/
public

Related

Symfony Invokable controllers called with render_esi

With Symfony, there is a possibility to create invokable controllers.
For some blocks like header or footer, i call my controller with twig function like this render(controller('App\\Controller\\MyInvokableController')) and it works.
But if i do the same with render_esi(controller('App\\Controller\\MyInvokableController')) i've this following error :
Cannot use object of type App\\Controller\\MyInvokableController as array
Is it possible to use invokable controller with render_esi ?
My controller :
declare(strict_types=1);
namespace App\Controller;
use ScemBundle\Helpers\EsiHelper;
use Symfony\Bridge\Twig\TwigEngine;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Twig\Error\Error;
/**
*
*/
final class MyInvokableController
{
use RepositoriesTrait;
/**
* #param Request $request
* #param EsiHelper $esiHelper
* #param TwigEngine $twig
*
* #return Response
* #throws Exception
*/
public function __invoke(Request $request, EsiHelper $esiHelper, TwigEngine $twig): Response
{
$params = $this->getSomeContent();
$content = $twig->render('#path/to/template.html.twig', $params);
$response = new Response();
$response
->setContent($content)
->setPublic()
->setSharedMaxAge(65536);
return $esiHelper->builEsiHeader($listItems, $response);
}
}

Class "Symfony\Bundle\FrameworkBundle\Controller\Controller" not found while loading "App\Controller\StudentController"

Hi I'm fresher for symfony . when i execute the below code it will show error.i installed all the assets of symfony.help me to clear this..!
<?php
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class StudentController extends Controller
{
/**
* #Route("/")
* #Method({"GET"})
*/
public function index()
{
// return new Response(
// '<html><body><h1>HI,Welcome to Tamilnadu</h1></body></html>'
// );
return $this->render('student/index.html.twig');
}
}
I just put "hello" in (student/index.html.twig),and i commented the basic response function and want to run the return this function.
Try this:
/**
* #Route("/", name="index")
* #return Response
*/
public function index():Response{
return $this->render('student/index.html.twig');
}

Symfony 4 How to autowire strings when making a general class?

I would first like to say that I saw the other questions on here relating to this error I'm having and none solved my problems.
I have the following code for a controller to check an APIkey before sending data from the backend to the frontend.
file1Controller.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class file1Controller extends AbstractController
{
/**
* #Route("/Some/URI", methods={"GET"}) // "/Some/URI" here
* #param Request $request
* #return JsonResponse
*/
public function list(Request $request)
{
if (empty($request->headers->get('api-key'))) {
return new JsonResponse(['error' => 'Please provide an API_key'], 401);
}
if ($request->headers->get('api-key') !== $_ENV['API_KEY']) {
return new JsonResponse(['error' => 'Invalid API key'], 401);
}
return new JsonResponse($this->getDoctrine()->getRepository('App:Something')->findAll()); //Something here
}
}
Which works exactly as intended (tested it with Postman and with my browser) for my simple learning example. I would like to generalize it so that I can use it in other places. Almost everything should stay the same except the parts where there are comments. This is what it becomes when making it general:
General.php
<?php
namespace App;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class General extends AbstractController
{
private $route;
private $entity;
/**
* General constructor.
* #param String $route
* #param String $entity
*/
function __construct(String $route, String $entity)
{
$this->route = $route;
$this->entity = $entity;
}
/**
* #Route({$this->route}, methods={"GET"})
* #param Request $request
* #return JsonResponse
*/
public function list(Request $request)
{
if (empty($request->headers->get('api-key'))) {
return new JsonResponse(['error' => 'Please provide an API_key'], 401);
}
if ($request->headers->get('api-key') !== $_ENV['API_KEY']) {
return new JsonResponse(['error' => 'Invalid API key'], 401);
}
return new JsonResponse($this->getDoctrine()->getRepository('App:{$this->entity}')->findAll());
}
}
And the file file1Controller.php changes to:
<?php
namespace App\Controller;
use App\General;
use Symfony\Component\HttpFoundation\Request;
class SubscriptionController
{
/**
* #return General
*/
public function AuthenticateAPI()
{
$generalObject = new General("/Some/URI", 'Something');
return $generalObject;
}
}
This new setup gives no compiler errors but of course, do give the following error (when testing it):
Cannot autowire service "App\General": argument "$route" of method "__construct()" is type-hinted "string", you should configure its value explicitly.
I understand that this error occurs because Symfony doesn't know which String to inject. But there must be a way to get around this? Because I can't specify the value explicitly in my case because I'll be making another file file2Controller.php which will be the exact same but with different $route and $entity.

How can I generalize an ApiKeyAuthenticator in Symfony 4?

I have the following code that checks whether the API-key is the correct one before sending data to the front end.
file1Controller.php
<?php
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class file1Controller extends AbstractController
{
/**
* #Route("/Some/URI", methods={"GET"}) // "/Some/URI" here
* #param Request $request
* #return JsonResponse
*/
public function list(Request $request)
{
if (empty($request->headers->get('api-key'))) {
return new JsonResponse(['error' => 'Please provide an API_key'], 401);
}
if ($request->headers->get('api-key') !== $_ENV['API_KEY']) {
return new JsonResponse(['error' => 'Invalid API key'], 401);
}
return new JsonResponse($this->getDoctrine()->getRepository('App:Something')->findAll()); //Something here
}
}
Which works excatly as intended (tested it with Postman) for my simple learning example. I would like to generalize it so that I can use it in other places. Almost everything should stay the same except the parts where there are comments. I have tried the following:
General.php
<?php
namespace App;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
class General extends AbstractController
{
private $request;
private $route;
private $entity;
/**
* ApiKeyAuthenticator constructor.
* #param Request $request
* #param String $route
* #param String $entity
*/
function __construct(Request $request, String $route, String $entity)
{
$this->request = $request;
$this->route = $route;
$this->entity = $entity;
}
/**
* #Route({$route}, methods={"GET"}) //notice here
* #return JsonResponse
*/
public function list()
{
if (empty($this->request->headers->get('api-key'))) {
return new JsonResponse(['error' => 'Please provide an API_key'], 401);
}
if ($this->request->headers->get('api-key') !== $_ENV['API_KEY']) {
return new JsonResponse(['error' => 'Invalid API key'], 401);
}
return new JsonResponse($this->getDoctrine()->getRepository('App:{$this->entity}')->findAll()); //notice here
}
}
Then I change the code of file1Controller.php to:
<?php
namespace App\Controller;
require(__DIR__.'/../General.php'); //note that there's no error accessing the file here
use Symfony\Component\HttpFoundation\Request;
class file1Controller
{
/**
* #param Request $request
*/
public function AuthenticateAPI(Request $request)
{
$AuthenticatorObject = new ApiKeyAuthenticator($request, "/Some/URI", 'Something'); //getting undefiend class
return $AuthenticatorObject;
}
}
This is unfortunately not working when testing it with Postman and I'm getting an undefiend class error on this line $AuthenticatorObject = new ApiKeyAuthenticator($request, "/Some/URI", 'Something'); in file1Controller.php
What did I do wrong and how could I fix it?
You shouldn't call your controllers like this in Symfony:
require(__DIR__.'/../General.php'); //note that there's no error accessing the file here
Please check out defining and accessing controllers as service in Symfony documentation:
How to Define Controllers as Services
How to Forward Requests to another Controller

FOSRestBundle : I can't see my new route

I've created a new controller (testController) which extends FOSRestController. I can't see the route "/test" i've created in this controller when I run symfony command "debug:router". With Postman, I've a 404 error...
I'm sure I forgot something but I don't know what. Here my code :
testController.php
<?php
namespace Project\ApiBundle\Controller;
use FOS\RestBundle\Controller\Annotations;
use FOS\RestBundle\Controller\Annotations as Rest;
use FOS\RestBundle\Controller\Annotations\Delete;
use FOS\RestBundle\Controller\Annotations\Get;
use FOS\RestBundle\Controller\Annotations\Post;
use FOS\RestBundle\Controller\Annotations\Put;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\View\RouteRedirectView;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use JMS\Serializer\SerializationContext;
/**
* Class testController.
*/
class testController extends FOSRestController
{
/**
* List .
* #ApiDoc(
* resource = true,
* statusCodes = {
* 200 = "Returned when successful"
* }
* )
*
* #Rest\View()
* #Get("/test")
*
* #param Request $request the request object
*
* #return array
*/
public function getTest(Request $request)
{
return "hello world";
}
}
And, here my routing.yml file :
api_test:
type: rest
resource: Project\ApiBundle\Controller\TestController
What I've forgot ?
Thank you very much !
I finally found the answer... so easy but I didn't see it ! The method name :
=> getTestAction

Resources