473,503 Members | 1,748 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Symfony, where is defined the Controller method getRepository?

103 New Member
1) Symfony, where is defined the method getRepository?

I have a line in the code:
$posts = $this->getDoctrine()->getRepository('ModelBundle:Post)->findAll();

i do not understand in which file is coded method:
getRepository('ModelBundle:Post).

2) Symfony, where is defined the method container->get('doctrine')?
3) It is not clear where is the folder “use Doctrine\Bundle\DoctrineBundle\Registry;” ?

1) I am in the lecture 27, second 29 in Udemy Course:
https://www.udemy.com/introduction-t...fony2/learn/#/
The course project can be download from:
https://github.com/davidmles/symfony2blog

But the downloaded project does not have vendor folder, thus it is not working and suitable for my questions about files in vendor folder.

This statement retrieves posts from the database:
Expand|Select|Wrap|Line Numbers
  1. $posts = $this->getDoctrine()->getRepository('ModelBundle:Post)->findAll();
It is not clear for me where is defined the method getRepository?


The PostController extends from Controller,
..\proj2\vendor\symfony\symfony\src\Symfony\Bundle \FrameworkBundle\Controller
Controller has a method “getDoctrine”, which call: $this->container->get('doctrine').

From where server knows about concatenated method "getRepository"?
$this->getDoctrine()->getRepository('ModelBundle:Post)

It is not clear from where we call method getRepository? I can not find it nor in the PostController, nor in the Controller.

2) The said Controller extends from ContainerAware
\vendor\symfony\symfony\src\Symfony\Component\Depe ndencyInjection\ContainerAware.php
which is an abstract class ContainerAware implementing ContainerAwareInterface
\vendor\symfony\symfony\src\Symfony\Component\Depe ndencyInjection\ContainerInterface.php
and has a variable $container
The container does not have method getRepository.
The container also does not define method "get" for the doctrine: container->get('doctrine'). The interface enumerates such a method. But the container does not implement. Where container->get('doctrine') is coded in Symfony?

3) PostController extends from Controller, which has a statement:
use Doctrine\Bundle\DoctrineBundle\Registry;
I am not able to find this Registry in the project file system. What is the full path starting from project folder?


Here is a full contents of file "PostController.php" and "Controller.php" .

Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. namespace Blog\CoreBundle\Controller;
  4.  
  5. use Blog\CoreBundle\Services\PostManager;
  6. use Blog\ModelBundle\Entity\Comment;
  7. use Blog\ModelBundle\Form\CommentType;
  8. use Symfony\Bundle\FrameworkBundle\Controller\Controller;
  9. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
  10. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  11. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  14.  
  15. /**
  16.  * Class PostController
  17.  *
  18.  * @Route("/{_locale}", requirements={"_locale"="en|es"}, defaults={"_locale"="en"})
  19.  */
  20. class PostController extends Controller
  21. {
  22.     /**
  23.      * Show the posts index
  24.      *
  25.      * @return array
  26.      *
  27.      * @Route("/")
  28.      * @Template()
  29.      */
  30.     public function indexAction()
  31.     {
  32.        $posts = $this->getDoctrine()->getRepository('ModelBundle:Post)->findAll();
  33.         $latestPosts = $this->getPostManager()->findLatest(5);
  34.  
  35.         return array(
  36.             'posts'       => $posts,
  37.             'latestPosts' => $latestPosts
  38.         );
  39.     }
  40. <...>
  41. }

Expand|Select|Wrap|Line Numbers
  1. <?php
  2.  
  3. /*
  4.  * This file is part of the Symfony package.
  5.  *
  6.  * (c) Fabien Potencier <fabien@symfony.com>
  7.  *
  8.  * For the full copyright and license information, please view the LICENSE
  9.  * file that was distributed with this source code.
  10.  */
  11.  
  12. namespace Symfony\Bundle\FrameworkBundle\Controller;
  13.  
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\HttpFoundation\Response;
  16. use Symfony\Component\HttpFoundation\RedirectResponse;
  17. use Symfony\Component\HttpFoundation\StreamedResponse;
  18. use Symfony\Component\DependencyInjection\ContainerAware;
  19. use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
  20. use Symfony\Component\HttpKernel\HttpKernelInterface;
  21. use Symfony\Component\Security\Core\Exception\AccessDeniedException;
  22. use Symfony\Component\Security\Csrf\CsrfToken;
  23. use Symfony\Component\Form\FormTypeInterface;
  24. use Symfony\Component\Form\Form;
  25. use Symfony\Component\Form\FormBuilder;
  26. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  27. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  28. use Doctrine\Bundle\DoctrineBundle\Registry;
  29.  
  30. /**
  31.  * Controller is a simple implementation of a Controller.
  32.  *
  33.  * It provides methods to common features needed in controllers.
  34.  *
  35.  * @author Fabien Potencier <fabien@symfony.com>
  36.  */
  37. class Controller extends ContainerAware
  38. {
  39.     /**
  40.      * Generates a URL from the given parameters.
  41.      *
  42.      * @param string      $route         The name of the route
  43.      * @param mixed       $parameters    An array of parameters
  44.      * @param bool|string $referenceType The type of reference (one of the constants in UrlGeneratorInterface)
  45.      *
  46.      * @return string The generated URL
  47.      *
  48.      * @see UrlGeneratorInterface
  49.      */
  50.     public function generateUrl($route, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH)
  51.     {
  52.         return $this->container->get('router')->generate($route, $parameters, $referenceType);
  53.     }
  54.  
  55.     /**
  56.      * Forwards the request to another controller.
  57.      *
  58.      * @param string $controller The controller name (a string like BlogBundle:Post:index)
  59.      * @param array  $path       An array of path parameters
  60.      * @param array  $query      An array of query parameters
  61.      *
  62.      * @return Response A Response instance
  63.      */
  64.     public function forward($controller, array $path = array(), array $query = array())
  65.     {
  66.         $path['_controller'] = $controller;
  67.         $subRequest = $this->container->get('request_stack')->getCurrentRequest()->duplicate($query, null, $path);
  68.  
  69.         return $this->container->get('http_kernel')->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
  70.     }
  71.  
  72.     /**
  73.      * Returns a RedirectResponse to the given URL.
  74.      *
  75.      * @param string $url    The URL to redirect to
  76.      * @param int    $status The status code to use for the Response
  77.      *
  78.      * @return RedirectResponse
  79.      */
  80.     public function redirect($url, $status = 302)
  81.     {
  82.         return new RedirectResponse($url, $status);
  83.     }
  84.  
  85.     /**
  86.      * Returns a RedirectResponse to the given route with the given parameters.
  87.      *
  88.      * @param string $route      The name of the route
  89.      * @param array  $parameters An array of parameters
  90.      * @param int    $status     The status code to use for the Response
  91.      *
  92.      * @return RedirectResponse
  93.      */
  94.     protected function redirectToRoute($route, array $parameters = array(), $status = 302)
  95.     {
  96.         return $this->redirect($this->generateUrl($route, $parameters), $status);
  97.     }
  98.  
  99.     /**
  100.      * Adds a flash message to the current session for type.
  101.      *
  102.      * @param string $type    The type
  103.      * @param string $message The message
  104.      *
  105.      * @throws \LogicException
  106.      */
  107.     protected function addFlash($type, $message)
  108.     {
  109.         if (!$this->container->has('session')) {
  110.             throw new \LogicException('You can not use the addFlash method if sessions are disabled.');
  111.         }
  112.  
  113.         $this->container->get('session')->getFlashBag()->add($type, $message);
  114.     }
  115.  
  116.     /**
  117.      * Checks if the attributes are granted against the current authentication token and optionally supplied object.
  118.      *
  119.      * @param mixed $attributes The attributes
  120.      * @param mixed $object     The object
  121.      *
  122.      * @return bool
  123.      *
  124.      * @throws \LogicException
  125.      */
  126.     protected function isGranted($attributes, $object = null)
  127.     {
  128.         if (!$this->container->has('security.authorization_checker')) {
  129.             throw new \LogicException('The SecurityBundle is not registered in your application.');
  130.         }
  131.  
  132.         return $this->container->get('security.authorization_checker')->isGranted($attributes, $object);
  133.     }
  134.  
  135.     /**
  136.      * Throws an exception unless the attributes are granted against the current authentication token and optionally
  137.      * supplied object.
  138.      *
  139.      * @param mixed  $attributes The attributes
  140.      * @param mixed  $object     The object
  141.      * @param string $message    The message passed to the exception
  142.      *
  143.      * @throws AccessDeniedException
  144.      */
  145.     protected function denyAccessUnlessGranted($attributes, $object = null, $message = 'Access Denied.')
  146.     {
  147.         if (!$this->isGranted($attributes, $object)) {
  148.             throw $this->createAccessDeniedException($message);
  149.         }
  150.     }
  151.  
  152.     /**
  153.      * Returns a rendered view.
  154.      *
  155.      * @param string $view       The view name
  156.      * @param array  $parameters An array of parameters to pass to the view
  157.      *
  158.      * @return string The rendered view
  159.      */
  160.     public function renderView($view, array $parameters = array())
  161.     {
  162.         return $this->container->get('templating')->render($view, $parameters);
  163.     }
  164.  
  165.     /**
  166.      * Renders a view.
  167.      *
  168.      * @param string   $view       The view name
  169.      * @param array    $parameters An array of parameters to pass to the view
  170.      * @param Response $response   A response instance
  171.      *
  172.      * @return Response A Response instance
  173.      */
  174.     public function render($view, array $parameters = array(), Response $response = null)
  175.     {
  176.         return $this->container->get('templating')->renderResponse($view, $parameters, $response);
  177.     }
  178.  
  179.     /**
  180.      * Streams a view.
  181.      *
  182.      * @param string           $view       The view name
  183.      * @param array            $parameters An array of parameters to pass to the view
  184.      * @param StreamedResponse $response   A response instance
  185.      *
  186.      * @return StreamedResponse A StreamedResponse instance
  187.      */
  188.     public function stream($view, array $parameters = array(), StreamedResponse $response = null)
  189.     {
  190.         $templating = $this->container->get('templating');
  191.  
  192.         $callback = function () use ($templating, $view, $parameters) {
  193.             $templating->stream($view, $parameters);
  194.         };
  195.  
  196.         if (null === $response) {
  197.             return new StreamedResponse($callback);
  198.         }
  199.  
  200.         $response->setCallback($callback);
  201.  
  202.         return $response;
  203.     }
  204.  
  205.     /**
  206.      * Returns a NotFoundHttpException.
  207.      *
  208.      * This will result in a 404 response code. Usage example:
  209.      *
  210.      *     throw $this->createNotFoundException('Page not found!');
  211.      *
  212.      * @param string          $message  A message
  213.      * @param \Exception|null $previous The previous exception
  214.      *
  215.      * @return NotFoundHttpException
  216.      */
  217.     public function createNotFoundException($message = 'Not Found', \Exception $previous = null)
  218.     {
  219.         return new NotFoundHttpException($message, $previous);
  220.     }
  221.  
  222.     /**
  223.      * Returns an AccessDeniedException.
  224.      *
  225.      * This will result in a 403 response code. Usage example:
  226.      *
  227.      *     throw $this->createAccessDeniedException('Unable to access this page!');
  228.      *
  229.      * @param string          $message  A message
  230.      * @param \Exception|null $previous The previous exception
  231.      *
  232.      * @return AccessDeniedException
  233.      */
  234.     public function createAccessDeniedException($message = 'Access Denied.', \Exception $previous = null)
  235.     {
  236.         return new AccessDeniedException($message, $previous);
  237.     }
  238.  
  239.     /**
  240.      * Creates and returns a Form instance from the type of the form.
  241.      *
  242.      * @param string|FormTypeInterface $type    The built type of the form
  243.      * @param mixed                    $data    The initial data for the form
  244.      * @param array                    $options Options for the form
  245.      *
  246.      * @return Form
  247.      */
  248.     public function createForm($type, $data = null, array $options = array())
  249.     {
  250.         return $this->container->get('form.factory')->create($type, $data, $options);
  251.     }
  252.  
  253.     /**
  254.      * Creates and returns a form builder instance.
  255.      *
  256.      * @param mixed $data    The initial data for the form
  257.      * @param array $options Options for the form
  258.      *
  259.      * @return FormBuilder
  260.      */
  261.     public function createFormBuilder($data = null, array $options = array())
  262.     {
  263.         return $this->container->get('form.factory')->createBuilder('form', $data, $options);
  264.     }
  265.  
  266.     /**
  267.      * Shortcut to return the request service.
  268.      *
  269.      * @return Request
  270.      *
  271.      * @deprecated since version 2.4, to be removed in 3.0.
  272.      *             Ask Symfony to inject the Request object into your controller
  273.      *             method instead by type hinting it in the method's signature.
  274.      */
  275.     public function getRequest()
  276.     {
  277.         @trigger_error('The '.__METHOD__.' method is deprecated since version 2.4 and will be removed in 3.0. The only reliable way to get the "Request" object is to inject it in the action method.', E_USER_DEPRECATED);
  278.  
  279.         return $this->container->get('request_stack')->getCurrentRequest();
  280.     }
  281.  
  282.     /**
  283.      * Shortcut to return the Doctrine Registry service.
  284.      *
  285.      * @return Registry
  286.      *
  287.      * @throws \LogicException If DoctrineBundle is not available
  288.      */
  289.     public function getDoctrine()
  290.     {
  291.         if (!$this->container->has('doctrine')) {
  292.             throw new \LogicException('The DoctrineBundle is not registered in your application.');
  293.         }
  294.  
  295.         return $this->container->get('doctrine');
  296.     }
  297.  
  298.     /**
  299.      * Get a user from the Security Token Storage.
  300.      *
  301.      * @return mixed
  302.      *
  303.      * @throws \LogicException If SecurityBundle is not available
  304.      *
  305.      * @see TokenInterface::getUser()
  306.      */
  307.     public function getUser()
  308.     {
  309.         if (!$this->container->has('security.token_storage')) {
  310.             throw new \LogicException('The SecurityBundle is not registered in your application.');
  311.         }
  312.  
  313.         if (null === $token = $this->container->get('security.token_storage')->getToken()) {
  314.             return;
  315.         }
  316.  
  317.         if (!is_object($user = $token->getUser())) {
  318.             // e.g. anonymous authentication
  319.             return;
  320.         }
  321.  
  322.         return $user;
  323.     }
  324.  
  325.     /**
  326.      * Returns true if the service id is defined.
  327.      *
  328.      * @param string $id The service id
  329.      *
  330.      * @return bool true if the service id is defined, false otherwise
  331.      */
  332.     public function has($id)
  333.     {
  334.         return $this->container->has($id);
  335.     }
  336.  
  337.     /**
  338.      * Gets a container service by its id.
  339.      *
  340.      * @param string $id The service id
  341.      *
  342.      * @return object The service
  343.      */
  344.     public function get($id)
  345.     {
  346.         if ('request' === $id) {
  347.             @trigger_error('The "request" service is deprecated and will be removed in 3.0. Add a typehint for Symfony\\Component\\HttpFoundation\\Request to your controller parameters to retrieve the request instead.', E_USER_DEPRECATED);
  348.         }
  349.  
  350.         return $this->container->get($id);
  351.     }
  352.  
  353.     /**
  354.      * Gets a container configuration parameter by its name.
  355.      *
  356.      * @param string $name The parameter name
  357.      *
  358.      * @return mixed
  359.      */
  360.     protected function getParameter($name)
  361.     {
  362.         return $this->container->getParameter($name);
  363.     }
  364.  
  365.     /**
  366.      * Checks the validity of a CSRF token.
  367.      *
  368.      * @param string $id    The id used when generating the token
  369.      * @param string $token The actual token sent with the request that should be validated
  370.      *
  371.      * @return bool
  372.      */
  373.     protected function isCsrfTokenValid($id, $token)
  374.     {
  375.         if (!$this->container->has('security.csrf.token_manager')) {
  376.             throw new \LogicException('CSRF protection is not enabled in your application.');
  377.         }
  378.  
  379.         return $this->container->get('security.csrf.token_manager')->isTokenValid(new CsrfToken($id, $token));
  380.     }
  381. }
  382.  
Sep 23 '15 #1
2 2372
Dormilich
8,658 Recognized Expert Moderator Expert
1) looks like a class from the Doctrine component.

2) looks like the Dependency Injection Container

3) that’s a namespace, not a folder. But I’d start searching in the vendor folder.

Note: above question can also be answered by a file system search (sensible editors offer the option to search strings in your project directory’s files)
Sep 24 '15 #2
gintare
103 New Member
Could anybody reply more clearly?
I do not understand the flow of the program.
Methods are concatenated which are not coded=described in the classes.
Oct 11 '15 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

2
1883
by: Martin Magnusson | last post by:
Hi, I have defined a method of a base class which writes to a C-style array without initializing it. (No, I don't like C arrays either, but I have to use it here because of another library I'm...
3
1759
by: cmay | last post by:
In reading some documents from the Patterns and Practices group, I had a question about the example given for the Page Controller pattern. (I have posted the code for the BasePage below) In...
15
21326
by: prabhdeep | last post by:
Hi, Can somebody explain, why in following code, i get "event not defined" error funcTest(sMenu) { doument.getElementById('id1').addEventListener('mousedown', function(){ click(sMenu,...
12
2270
by: Ramon | last post by:
Hello I'm new to OOP in PHP and I have this question: I have a class called "Form", which contains a collection of classes (objects) called "Textbox". Now I need to call the Textbox class's...
0
1082
by: jphaycock | last post by:
I have a formview that uses an objectdatasource to insert and update records. I don't want to use the objectdatasource's "Delete" method so I have defined this method as "none" in the "configure...
1
1738
by: shapper | last post by:
Hello, I am converting some old code from VB.NET to C# using an online converter but I still get a few errors: public static Object Settings() { return...
7
4690
by: Andrus | last post by:
How to get syntactically correct signature which compiles for code template grneration ? I tried code below but it creates syntactically incorrect signature. Andrus. using System; using...
1
22086
by: satishch | last post by:
I would like to call spring mvc method when ever onUnload. So i write the code in <body onUnload="bye()"></body> In javascript ------------- <script type="text/javascript"> ...
0
1281
by: user033088 | last post by:
I have defined a method in Form1 which uses the RunWorkerCompletedEventArgs as follows public void CallFun(object sender, RunWorkerCompletedEventArgs e) { ...
0
7258
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
7313
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
1
6970
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7441
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
5558
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
1
4987
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4663
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
1
720
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
366
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.