Refactor The Laravel Regex Tool To Use Repositories and Dependency Injection

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 on learning how to refactor, “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.

laravelappcontrollersRegexController.php source


use thedomainrepositoriesregexrepositoryRegexRepositoryInterface;
use thedomainrepositoriesvalidationrepositoryValidationRepositoryInterface;

class RegexController extends BaseController
    protected $regex;
    protected $validator;

    public function __construct(RegexRepositoryInterface $regex, ValidationRepositoryInterface $validator)
        $this->regex = $regex;
        $this->validator = $validator;

    public function index()
        $result = Session::get('result');
        $message = Session::get('message');
        return View::make('regex')->with(['result' => $result, 'message' => $message]);

    public function match()
        $data = Input::all();
        $rules = ['subject' => 'required', 'pattern' => 'required'];
        $haserrors = $this->validator->haserrors($data, $rules);

        if ($haserrors) {
            return Redirect::to('/regex2')->withInput()->withErrors($haserrors);
        } else {
            $result = $this->regex->match($data['subject'], $data['pattern']);
            return Redirect::to('/regex2')->withInput()->with(['result' => $result]);
laravelapproutes.php source


Route::get('/regex2', 'RegexController@index');
Route::post('/processregex2', 'RegexController@match');
laravelappviewsregex.blade.php source


    {{ Form::open( ['url' => '/processregex2'] ) }}

    {{ Form::label('subject', 'Enter the haystack here.') }}
    {{ Form::textarea('subject', '', ['class' => 'form-control']) }}
    {{  $errors->first('subject', '<div class="alert alert-danger"><b>:message</b></div>')  }}
    {{ Form::label('pattern', 'Enter your regex pattern here.') }}
    {{ Form::text('pattern', '', ['class' => 'form-control']) }}
    {{  $errors->first('pattern', '<div class="alert alert-danger"><b>:message</b></div>')  }}
    {{ Form::submit('Preg Match All', ['class' => 'btn btn-info']) }}

    {{ Form::close() }}
        @if(count($result) > 0 )
            <div class="alert alert-success">Here are your matches</div>
            @foreach( $result as $match )
                {{ $match }} <br>
            <div class="alert alert-info">Sorry No Matches</div>
        <div class="alert alert-danger"> {{ $result  }} </div>

laravelappviewslayoutsmaster.blade.php source
<!doctype html>


    <script src=""></script>
    <link rel="stylesheet" href="//">
    <script src="//"></script>
    <meta charset="utf-8">
    <title>Regex Test</title>

<div class="container">
        <h1>Laravel Regex Tester</h1>

        <p class="lead">Test a regex.</p>
    <div class="row">
        <div class="col-sm-8 blog-main"> @yield('content') </div>


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.

thedomainrepositoriesregexrepositoryRegexRepositoryInterface.php source

namespace thedomainrepositoriesregexrepository;

interface RegexRepositoryInterface
    public function match($subject, $pattern);
thedomainrepositoriesvalidationrepositoryValidationRepositoryInterface.php source


namespace thedomainrepositoriesvalidationrepository;

interface ValidationRepositoryInterface
    public function haserrors($data, $rules);

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.

thedomainrepositoriesregexrepositoryRegexRepository.php source

namespace thedomainrepositoriesregexrepository;

use Exception;

class RegexRepository implements RegexRepositoryInterface
    public function match($subject, $pattern)
        try {
            preg_match_all('/' . $pattern . '/', $subject, $matches);
        } catch (Exception $e) {
            $error = $e->getMessage();
            return $error;

        $result = array();
        if (sizeof($matches[0]) > 0) {
            foreach ($matches[0] as $match) {
                $result[] = $match;

        return $result;
thedomainrepositoriesvalidationrepositoryValidtionRepository.php source

namespace thedomainrepositoriesvalidationrepository;

use Validator;

class ValidationRepository implements ValidationRepositoryInterface
    public function haserrors($data, $rules)
        $validation = Validator::make($data, $rules);
        if ($validation->fails()) {
            $errors = $validation->messages();
            return $errors;
        return false;

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.

thedomainrepositoriesregexrepositoryBackendServiceProvider.php source

namespace thedomainrepositoriesregexrepository;

use IlluminateSupportServiceProvider;

class BackendServiceProvider extends ServiceProvider

    public function register()
        $this->app->bind('thedomainrepositoriesregexrepositoryRegexRepositoryInterface', 'thedomainrepositoriesregexrepositoryRegexRepository');
thedomainrepositoriesvalidationrepositoryBackendServiceProvider.php source

namespace thedomainrepositoriesvalidationrepository;

use IlluminateSupportServiceProvider;

class BackendServiceProvider extends ServiceProvider

    public function register()
        $this->app->bind('thedomainrepositoriesvalidationrepositoryValidationRepositoryInterface', 'thedomainrepositoriesvalidationrepositoryValidationRepository');

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.

laravelappconfigapp.php source

	'providers' => array(



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.

laravelcomposer.json source
  "autoload": {
    "classmap": [
    "psr-4": {
      "thedomain\": "app/thedomain"

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


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 🙂