03.12.2015 Views

laravel4cookbook

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Controller Testing 362<br />

14<br />

15 public function insert()<br />

16 {<br />

17 $data = [<br />

18 "title" => $this->request->get("title"),<br />

19 "subtitle" => $this->request->get("subtitle"),<br />

20 "body" => $this->request->get("body"),<br />

21 "author_id" => $this->request->get("author"),<br />

22 "slug" => Str::slug($this->request->get("title"))<br />

23 ];<br />

24<br />

25 // insert posts with $data...<br />

26 }<br />

.<br />

This was extracted from app/Formativ/PostRepository.php.<br />

Using this approach, you can delegate method calls based on events, rather than explicit method<br />

calls and variable manipulation.<br />

.<br />

There are loads of different ways to use events, so you should definitely check out the official docs<br />

at: http://laravel.com/docs/events.<br />

http://laravel.com/docs/events<br />

This Isn’t Testing!<br />

If you’re wondering how this is related to testing, consider how you would have tested the original<br />

controller code. There are many different responsibilities, and places for errors to emerge.<br />

Splitting off your logic into classes of single responsibility is a good thing. Generally following<br />

SOLID principles is a good thing. The smaller your classes are, the fewer things each of them do,<br />

the easier they are to test.<br />

So how would we write tests for these new classes? Let’s begin with one of the concrete implementations:

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!