Upgrade to Pro — share decks privately, control downloads, hide ads and more …

QueryFilter: Model Filtering

QueryFilter: Model Filtering

Filtering gives you a bunch of options. Many options and conditionals make your controller bigger and bigger. Let's use the QueryFilter concept to map all query string parameters with our model layer, cleaning up your controller.

Talk presented on Darkmira Tour PHP 2018, in Brasília, DF Brazil,

Junior Grossi

April 14, 2018

More Decks by Junior Grossi

Other Decks in Technology


  1. QueryFilter: Model Filtering Junior Grossi @ Darkmira Tour PHP 2018

    April 2018
  2. About me @junior_grossi

  3. Resume PHPMG group organizer Software Engineer at InterNACHI (PHP/Laravel) Creator

    of Corcel PHP Ph.D. in Information Science ‑ UFMG 2018 (in progress) Master's in Information Science ‑ UFMG 2015 Specialization in Web Developmenet ‑ PUCMG 2013 MBA in Business Management ‑ FGV 2009 Bachelor's in Computer Science ‑ PUCMG 2007 Zend Certified Engineer ‑ 2011
  4. Contact GitHub: http://github.com/jgrossi Twitter: http://twitter.com/junior_grossi Blog: https://blog.jgrossi.com

  5. Talk's dynamics 35' talk + 5' questions = 40' 20%

    slides + 80% live coding
  6. What's QueryFilter ? Code abstraction for filtering objects based on

    the `URL. From Laracasts: http://laracasts.com
  7. /posts?title=foo&status=bar Select Post which title contains foo ; Select Post

    which status is bar .
  8. Example Listing posts in JSON format Posts from WordPress http://blog.jgrossi.com

    Using Corcel PHP http://github.com/corcel/corcel Use WordPress backend with Laravel or any PHP app Laravel 5.6 app to handle all the logic
  9. composer require jgrossi/corcel

  10. Listing posts in JSON public function index() { $posts =

    Post::newest()‑>limit(10)‑>get(); return PostResource::collection($posts); // json }
  11. Filtering by Request public function index(Request $request) { $query =

    Post::query()‑>newest()‑>limit(10); if ($request‑>filled('title')) { $value = $request‑>get('title'); $query‑>where('post_title', 'like', "%$value%"); } if ($request‑>filled('status')) { $query‑>where('post_status', $request‑>get('status' } $posts = $query‑>get(); return PostResource::collection($posts); }
  12. Filtering by QueryFilter SOLID's Single responsibility principle ... a class

    should have only a single responsibility. Dependency/Method Injection ... is a technique whereby one object supplies the dependencies of another object.
  13. Show me the code Talk is cheap. Show me the

    code. ‑‑ Linus Trovals
  14. After 20 minutes of live coding...

  15. QueryFilter is a concept

  16. Update: Talk's code https://github.com/jgrossi/darkmira‑query‑filter

  17. Composer Packages cerbero/query‑filters kblais/query‑filter

  18. Thanks! Questions? GitHub: http://github.com/jgrossi Twitter: http://twitter.com/junior_grossi Blog: https://blog.jgrossi.com