Refactor The Laravel Regex Tool To Use Repositories and Dependency Injection

Thanks For Sharing! :-)Share on Google+Tweet about this on TwitterShare on FacebookShare on RedditBuffer this page

Refactor The Laravel Regex Tool To Use Repositories and Dependency Injection

Welcome back gang to another fun filled episode of working with Laravel for fun and profit. Well, fun at least. In this episode, we’ll be taking a closer look at the regular expression tool we built earlier. Admittedly, this is a purely hacked together rendition created for fun really. I thought it might be a good idea for us to apply the repository pattern with dependency injection, interfaces, and namespaces to this tool to see how we would do that. This way, we have both approaches covered. The hacker approach, and the carefully planned approach. John Resig once said, “Just get something working, then you can refactor.” With that, we’ll take our MVP or MVRT (Minimum Viable Regex Tester) and re engineer this thing for the good of humanity. Let’s check it out.


Controllers Routes and Views

First off, we’ll look at the controller we create for this project which is RegexController.php, the routes.php file, as well as the view. This is the top layer so to speak. Underneath all of this are the repositories that make it happen.

laravel\app\controllers\RegexController.php source

laravel\app\routes.php source

laravel\app\views\regex.blade.php source

laravel\app\views\layouts\master.blade.php source

Cool! The above files are pretty much the whole application (minus the plumbing underneath), but this gives an idea of how to better layout the application design. Our first attempt, thought it works, is a hackish mess. With this iteration, we have one fairly clean controller, a couple of lines in the routes file, and a couple of views. The actual functionality of the app is exactly the same. It just shows how problems can be solved with *very* different approaches (You just want to gravitate towards the approaches that will keep you sane).


The Supporting Cast

Thanks to Laracasts and Jeffrey Way, the Laravel and PHP Community as a whole has a fantastic resource for learning about advanced application design and programming best practices. I just wanted to give a shout out where credit is due, as this pattern here is inspired by Jeff’s teachings.

Since we’re going to be applying the repository pattern, we’ll follow roughly the steps outlined in an earlier post about repositories. This is the outline we’ll follow. It’s just slightly modified from our prior version to make sure we are covering all steps.

1. Create The Domain Folder

This is the root namespace of your application. If your application is named awesome, then the folder or directory has the name of awesome. In this case, we’ll name the directory as “thedomain“, so this will remind us as we work through the example that this is the root domain level folder.

2. Create Repository Sub Directories

Most projects are going to have multiple repositories, so go ahead and create sub directories for those as well. In this example we are going to have a repository for our regular expression processing as well as a repository for validation processing. The two directories we’ll use are regexrepository and validationrepository to hold our regular expression repository files and validation repository files respectively. Each subdirectory will hold three PHP files. One for the interface, One for the actual repository (the code that does the processing), and one for the back end service provider.

3. Create Your Interfaces

Now we will create an interface for each repository. The regex repository will use the RegexRepositoryInterface while the validation repository will use the ValidationRepositoryInterface. Be sure to create each in the correct folder, and assign the namespace in each file. Here are the two files we need to create.

thedomain\repositories\regexrepository\RegexRepositoryInterface.php source

thedomain\repositories\validationrepository\ValidationRepositoryInterface.php source

4. Create The Repository

With both interfaces created, we can now create the actual repository that implements the interfaces. Remember, the interface just tells us the outline we need to follow in the implementation. Here are the two implementations that we created for the interfaces.

thedomain\repositories\regexrepository\RegexRepository.php source

thedomain\repositories\validationrepository\ValidtionRepository.php source

5. Create The Service Provider

Since we are typehinting an interface in the controller, we need Laravel to know what class to use for the interface. We do this with the backend service providers that bind a class to an interface. Here are the two backend service providers that we created.

thedomain\repositories\regexrepository\BackendServiceProvider.php source

thedomain\repositories\validationrepository\BackendServiceProvider.php source

Again, with this pattern you’ll see three files per repository folder – the interface file, the repository file, and the backend service provider file. We are now all set with those here.

6. Update The Provider Array

In order for all of the legwork we’ve done so far to be functional, we need to add the backend service providers to the providers array in app.php. Here is how we updated ours. Note the two new entries at the end of the array.

laravel\app\config\app.php source

7. Update Composer Dot JSON

Another step we must take before any of this works is to set up PSR-4 Namespacing in the composer.json file. In the autoload section of the composer.json, we need to add an entry for PSR-4. It follows the convention of "thedomain\\" : "app/thedomain", where the information to the left of the colon is your root namespace, and the information to the right of the colon is where to find that namespace.

laravel\composer.json source

8. Run Composer Dump

We are not done yet! Finally, we must run composer dump in order to generate the autoloading files for the application.


So Does It Work?

Great question, let’s find out!


Loading Up The Application works

laravel regex tester


Forgetting The Subject works

laravel regex validation two


Forgetting The Pattern works

laravel regex validation


A Successful Match or Matches works

laravel regex success
laravel regex success two

No Matches Found works

laravel regex no matches

Exception Thrown works

laravel regex handled exception

Conclusion

That was a lot of fun. It looks like everything works too! See, there is reason to believe in miracles. Thanks for stopping by, share this post with a friend if you like :-)

Thanks For Sharing! :-)Share on Google+Tweet about this on TwitterShare on FacebookShare on RedditBuffer this page

Build A Regular Expression Tester With Laravel

Thanks For Sharing! :-)Share on Google+Tweet about this on TwitterShare on FacebookShare on RedditBuffer this page

Build A Regular Expression Tester With Laravel

In the last episode we built a bare bones regular expression tester using PHP. It does what we need it to, but its really limited, and doesn’t look that great. In this episode, we are going to Larafy it. We’re going to re build the regular expression tester using Laravel. This should be a good test of hacking something quick and dirty together using native PHP versus building it in a framework like Laravel. The two approaches are really different, and this little exercise will give us a good idea of how to change up our thinking. Let’s check it out.


Laravel 4.2

For this example, we’re going to make use of Laravel 4.2. Though we’re all looking forward to Laravel 5 and all of the cool new features it has – it still is a moving target as things change so we’ll stick with Laravel 4.2 for now. We’re going to mimic what we did in the first iteration of this project without a framework. This is the first iteration with Laravel, and I’m taking the approach of simply, get something working, then worry about refactoring later. So that is what we’ll do.

routes.php

master.blade.php

regex.blade.php

These three files make up the application. Let’s test it out.

Visiting The App For The First Time

First up, we just want to make sure that when we visit the regular expression tester, that it loads properly and we don’t get any random errors or messages that shouldn’t be there. We visit http://localhost/laravel/public/ and all looks well.
laravel regular expression tester

Submitting A Regex Test With No Pattern

We test the validation by submitting a test without filling in the regex pattern. We see the validation working great, as we get the error message as shown here.
laravel regex validation

Submitting A Regex Test With No Subject

Testing the form without including a subject shows validation working here as well.
laravel regex validation two

Example of Successful Regex Matches

Now that we see how the basic validation is working, lets test out some actual regex matching with a valid subject and pattern. We can see that by submitting our test, we get a nice flash message back with the number of matches each on a new line. In this case we matched ‘Laravel’ and found two matches. Cool!
laravel regular expression successful match

What Happens When There Are No Matches?

We need to account for when there are no matches for our regular expression test. This is built in and we can test this out now. What’s nice is that we can leave our test string in place in the subject text area, since we have the application set up to repopulate the form on each iteration. Our current string of ‘This is some example text about Laravel and we’ll match Laravel with a regular expression now.’ has no numbers, so lets’ try to match a number with a regular expression to see how the app handles this. We can see that when trying to match a digit, we get a nice error message like so.
laravel regular expressions no matches

Catching Exceptions in our Little Laravel App

There will be instances when we provide a pattern to the application that is not understood by the preg_match_all function under the hood. In those cases, we want to catch the exception that gets thrown, and display it in a nice way. Otherwise, we’ll get the usual ugly failures that we see when PHP fails on a script. Due to the try catch sequence we included in the logic, this works out pretty good as well. In this example we can see a message of preg_match_all(): Unknown modifier ‘d’.
regex catch exceptions

Conclusion

This was a fun little test of hacking together a quick and dirty regular expression tester in Laravel. We made use of basic routes, Laravel Blade templating, Laravel Validation, and some good old fashioned native PHP to accomplish our goal. Thanks for checking it out.

Thanks For Sharing! :-)Share on Google+Tweet about this on TwitterShare on FacebookShare on RedditBuffer this page