Advertisement
tranquangchau

best practic symfony

May 20th, 2015
218
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 8.17 KB | None | 0 0
  1. <?php
  2. public function executeAddToCart(sfWebRequest $request)
  3. {
  4.     $this->form = new CartForm();
  5.     if($this->isMethod('post')&& $this->form->bindAndSave($request->getParameter('cart')))
  6.     {
  7.         $this->getUser()->setFlash('notice','Items have been added to your cart');
  8.         $this->redirect('@payment');
  9.     }
  10. }
  11. //in a controller
  12. public function executeRecentProducts(sfWebRequest $request)
  13. {
  14.     $this->products = Doctrine::getTable('Product')
  15.         ->createQuery('p')
  16.         ->where('p.is_published=1')
  17.         ->orderBy('published_at DESC')
  18.         ->limit(10)
  19.         ->fetchArray();
  20. }
  21.  
  22. //in a controller
  23. public function executeRecentProducts(sfWebRequest $request)
  24. {
  25.     $this->products = ProductTable::getRecents($max = 10,$published = true);
  26. }
  27. //1:
  28. class myWebRequest extends sfWebRequest
  29. {
  30.     public function getHttpRowPostData()
  31.     {
  32.         if(!this->isMethod('post'))
  33.         {
  34.             return;
  35.         }
  36.         return trim(file_get_contents('php://input'));
  37.     }
  38. }
  39. //2
  40. //in a controller
  41. public function executeProcess(myWebRequest $equest)
  42. {
  43.     $postContent = $request -> getHttpRowPostData();
  44.     //...
  45. }
  46. //3
  47. // #factories.yml
  48. /*
  49. all:
  50.     request:
  51.         class: myWebRequest
  52. */
  53.  
  54.  
  55. //in the template
  56. /*
  57. <?php if ($sf_request->hasParameter('foo')); ?>
  58. <p class="ok"> Hax foo: <?php echo $sf_request->getParameter('foo') ?></p>
  59. <?php else: ?>
  60. <p class="ko"> Haz't foo</p>
  61. <?php endif;?>
  62.  
  63. <?php if(count($foo)); ?>
  64. <?php foreach ($foo as $bar): ?>
  65.     <p><?php echo $bar ?></p>
  66. <?php endforeach; ?>
  67. <?php endif;?>
  68. */
  69.  
  70. class invoicesActions extends sfActions
  71. {
  72.     /**
  73.     * List all avaliable invoices
  74.     *
  75.     *@param sfWebRequest $request The HTTP request
  76.     */
  77.     public function executelistInvoices(sfWebRequest $request)
  78.     {
  79.         $this->invoices = InvoicePeer::retrieveAll($request->getParameter('type'));
  80.     }
  81. }
  82.  
  83. //in a controller
  84. public function executeMakeSandwich()
  85. {
  86.     try
  87.     {
  88.         $this->sandwich =SandwichMake::makeSandwich();
  89.         $this->getUser()->setFlash('notice','Your sandwich is ready');
  90.     }
  91.     catch(HomeException $e)
  92.     {
  93.         $this->logMessage('Problem with ham: '. $e->getMessage(), 'err');
  94.         $this->getUser()->setFlash('error','Can\t make the sandwich,try with sude');
  95.     }
  96.     $this->redirect('@make_sandwich');
  97. }
  98.  
  99. protected function buildQuery()
  100. {
  101.     $tableMethod = $this->configuration >getTableMethod();
  102.     if(is_null($this->filters))
  103.     {
  104.         $this->filters = $this->configuration->getFilterForm($this->getFilters());
  105.     }
  106.     $this->filters->setTableMethod($tableMethod);
  107.     $query = $this->filters->buildQuery($this->getFilters());
  108.     $this->addSoftQuery($query);
  109.     $event = $this->disatcher->filter(new sfEvent($this, 'admin.build_query'),$query);
  110.     $query = $event->getReturnValue();
  111.    
  112.     return $query;
  113. }
  114.  
  115. //in a controller
  116. public function executeMakeCoffe(sfWebRequest $request)
  117. {
  118.     $this->getUser()->makeCoffe($request->getParmeter('beans', array()));
  119. }
  120. //in myUser (or any sfUser derivated class)
  121. public function makeCoffe($beans)
  122. {
  123.     $coffeeDrops = array();
  124.     foreach($beans as $bean)
  125.     {
  126.         $coffeeDrops[] = CoffeeMaker::mill($bean)->infuse();
  127.     }
  128.     $this->setAttribute('coffee', implode('~',$coffeeDrops));
  129. }
  130. // in a controoler
  131. public function executeRecentlySeenProducts(sfWebRequest $request)
  132. {
  133.     $this->products = Doctrine::getTable('Product')
  134.         ->createQuery('p')
  135.         ->select('p.id')
  136.         ->where('is_published=1')
  137.         ->limit(10)
  138.         ->fetchArray(); //array(1,2,3)
  139.     $this->getUser()->setAttribute('recentlySeenProducts',$this->products);
  140. }
  141.  
  142. //1
  143. //the model
  144. class Story extends BaseStory
  145. {
  146.     protected $sf_user= null;
  147.     public function __construct(sfUser $sf_user)
  148.     {
  149.         $this->sf_user = $sf_usre;
  150.     }
  151.     public function save($con = null)
  152.     {
  153.         if($this->sf_user instanceof sfBasicSecurityUser)
  154.         {
  155.             $this->created_by = $this->sf_user->getId();
  156.         }
  157.         return parent::save($con);
  158.     }
  159. }
  160. //2
  161. //the controller
  162. class StoryAction extens sfAction
  163. {
  164.     public function executeCreate(sfWebRequest $request)
  165.     {
  166.         $story = new Story($this->getUser());
  167.         $story->fromArray($request->getParameter('story'));
  168.         $story->save();
  169.     }
  170. }
  171. // the model
  172. class Story extends BaseStory
  173. {  
  174. }
  175. //the controller
  176. class sstoryAction extends sfAction
  177. {
  178.     public function executeCreate($request)
  179.     {
  180.         $story = new Story();
  181.         $story->fromArray(array_merge($request->getParameter('story',array()), array('created_by'=>$this->getUser()->getId())));
  182.         $story->save();
  183.     }
  184. }
  185. //factories.yml
  186. /*
  187. dev:
  188.     logger:
  189.     class: sfAggregateLogger
  190.     param:
  191.         level: debug
  192.         loggers:
  193.             sf_web_debug:
  194.                 class:sfWebDebugLogger
  195.                 param:
  196.                     level:debug
  197.                     condition: %SF_WEB_DEBUG
  198.                     xdebug_logging: false
  199.                     web_debug_class:sfWebDebugForSf12
  200. */
  201. //1
  202. //in a controller
  203. public function executeList(sfWebRequest $request)
  204. {
  205.     $this->posts = PostTable::getRecents(sfConfig::get('app_blog_max_items',10));
  206. }
  207. //2
  208. //app.yml file
  209. /*
  210. all:
  211.     blog:
  212.         max_items:10
  213. */
  214.  
  215. //#routing.yml
  216. /*
  217. homepage:
  218.     path: /{_locale}
  219. ticket_index:
  220.     path: /{_locale}/tickets
  221. tickets_detail:
  222.     path: /{_locale}/tickets/{id}
  223. tickets_create:
  224.     path: /{_locale}/tickets/create
  225. login:
  226.     path: /login
  227.  
  228. //#routing.yml
  229. homepage:
  230.     path: /{_locale}
  231.     requirements: {_locale: "(nl|fr|en)"}
  232. ticket_index:
  233.     path: /{_locale}/tickets
  234.     requirements: {_locale: "(nl|fr|en)"}
  235. tickets_detail:
  236.     path: /{_locale}/tickets/{id}
  237.     requirements: {_locale: "(nl|fr|en)", id: "[1-9][0-9]*"}
  238. tickets_create:
  239.     path: /{_locale}/tickets/create
  240.     requirements: {_locale: "(nl|fr|en)"}
  241. login:
  242.     path: /login
  243.  
  244. //#services.yml
  245. parameters:
  246.     available_locales: [nl,fr,en]
  247. services:
  248.     check_locale_listener:
  249.         class: CheckLocaleListener
  250.         arguments: [%available_locales%]
  251.         tags:
  252.             - name: kernel.event_listener
  253.             event: kernel.request
  254.             method: checkLocale
  255.             priority: 24
  256. */
  257.  
  258. //1 doan trong php
  259. namespace KingFoo\Presentation\Controller\BlogPost;
  260.  
  261. use Doctrine\Common\Presistence\ObjectManager;
  262. use Symfony\Componet\HttpFoundation\Request;
  263.  
  264. class CreateController
  265. {
  266.     public function _construct(ObjectManager $manager)
  267.     {
  268.         //...
  269.     }
  270.     public function _invoke(Request $request)
  271.     {
  272.         //...
  273.     }
  274.     public function _invoke1(Request $request)
  275.     {
  276.         if(!this->authorizationChecker->isGranted('ROLE_EDITOR'))
  277.         {
  278.             throw new AccessDeniedHttpException();
  279.         }
  280.         $response = new Response();
  281.         $response->setMaxAge(3600);
  282.         return $this->templating->renderResponse(
  283.             'blog_post/create.html.twig',
  284.             array(
  285.                 //view parameters
  286.             ),
  287.             $response
  288.         );
  289.     }
  290. }
  291.  
  292. //ghe
  293. use Sensio\Bundle\FrameworkExtraBundle\Configration\Cache;
  294. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
  295. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
  296. use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
  297.  
  298. /**
  299.  *@Route(service="blog_post_crete_controller")
  300.  */
  301. class CreateController
  302. {
  303.     /**
  304.      *@Route("/blog/create", name="foo")
  305.      *@Cache(maxege=3600)
  306.      *@Security("has_role('ROLE_EDITOR')")
  307.      *@Template("blog_post/create.html.twig")
  308.      */
  309.     public function _invoke(Request $request)
  310.     {
  311.         return array(
  312.             //view parameters
  313.         );
  314.     }
  315. }
  316.  
  317. //nghi la su dung 3 thu vien nya
  318. use SymfonyComponentHttpFoundationCookie;
  319. use SymfonyComponentHttpFoundationRequest;
  320. use SymfonyComponentHttpFoundationStreamedResponse;
  321. class BetterController
  322. {
  323.     public function __invoke(Request $request)
  324.     {
  325.         $template = $request->query->get('template');
  326.         $response = new StreamedResponse(
  327.             function() use ($template)
  328.             {
  329.                 $this->archaicPdfLib->output($template);
  330.                 }
  331.             );
  332.             $cookie = new Cookie('lastGeneration', time());
  333.             $response->headers->setCookie($cookie);
  334.         return $response;
  335.     }
  336. }
  337.  
  338. //security.yml
  339. //access_control:
  340. //  -{path: ^/(nl|fr|en)/admin, roles:ROLE_ADMIN}
  341.  
  342. //
  343. class AdminController
  344. {
  345.     /*
  346.     *@Route("/{_locale}/admin")
  347.     *@Security("has_role('ROLE_ADMIN')")
  348.     */
  349.     public function _invoke(Request $request)
  350.     {
  351.         //if (!this->authorizationChecker->isGranted('ROLE_ADMIN')){
  352.         //  throw new AccessDeniedHttpException();
  353.         // }
  354.     }
  355. }
  356.  
  357. //use Bcrypt
  358. #security.yml
  359. /*
  360. security:
  361.     encoders:
  362.         KingFoo\Presentation\Security\user:
  363.             algorithm: bcrypt
  364.             cost:13
  365.  
  366. security:
  367.     password_encoder:
  368.         class: Symfony\Component\Security\...\BCryptPasswordEnoder
  369.         arguments: [13]
  370.  
  371. security:
  372.     encoders:
  373.         KingFoo\Presentation\Security\user:
  374.             id: password_encoder
  375. */
  376.            
  377.  
  378. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement