Posted By

denis_nizetichotmailcom on 10/22/11


Tagged

service


Versions (?)

Symfony 2 Services


 / Published in: Symfony
 

  1. Create a service class:
  2.  
  3. 1) make a directory at bundle root: /Services
  4.  
  5. 2) put a class there, e.g.
  6.  
  7. <?php
  8.  
  9. namespace Penny\HomeBundle\Services;
  10.  
  11.  
  12. use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
  13. use Symfony\Component\Security\Core\SecurityContext;
  14.  
  15.  
  16.  
  17. class MySecurity
  18. {
  19.  
  20. //import security.context
  21. public function __construct()
  22. {
  23.  
  24. }
  25.  
  26. /**
  27. *
  28. * Check which entities user
  29. * can edit/delete
  30. * parameter: User entity
  31. */
  32.  
  33. public function belongsToUser($entity, $user_id)
  34. {
  35. //$s = new SecurityContext(new AuthenticationManagerInterface());
  36. //$id = $s->getToken()->getUser()->getId();
  37. $id = $this->get('security.context')->getToken()->getUser()->getId();
  38. return $user_id === $entity->getUser()->getId();
  39. }
  40. }
  41.  
  42.  
  43. ?>
  44.  
  45. 3) change app/config/config.yml - add service class to it:
  46.  
  47. parameters:
  48. items_per_page: 8
  49.  
  50. services:
  51. my_security:
  52. class: Penny\HomeBundle\Services\MySecurity
  53. paginated_query:
  54. class: Penny\HomeBundle\Services\PaginatedQuery
  55. arguments: [%items_per_page%, @security.context]
  56.  
  57. 4) in action:
  58.  
  59. //class name //method
  60. $this->get('paginated_query')->getResult($query, $page_num);

Report this snippet  

You need to login to post a comment.