It’s seldom that we need to extend Laravel’s core, and even when we do, it’s most likely we’re going to extend specific components, which is detailed in the docs.

However, all of these instructions presume you’re using the core Laravel (IOC Container) to extend the other classes. What if you want to extend the Application itself?

This Is Actually A Real Example

This has come up recently because some folks are debating on whether or not Laravel 5 should make it easier to change the default folder paths–e.g. changing storage‘s location, or changing public to be public_html. There are, at the time of this writing, no easy ways to do that other than Application, and that has some folks worried.

So, let’s do it. Let’s take a Laravel 5 application, extend its Application, and change its storage path to be /OMGStorage.

Extend it

First, create an application class somewhere in your namespace, and have it extend IlluminateFoundationApplication. For example:

<?php namespace Confomo;

class Application extends IlluminateFoundationApplication
{
}

Register it

Now, let’s find where IlluminateFoundationApplication is bound. Thankfully, it’s simple: bootstrap/app.php. The first non-comment code in the file is:

$app = new IlluminateFoundationApplication(
    realpath(__DIR__.'/../')
);

I think you can guess what’s coming next. Just replace those lines with these:

$app = new ConfomoApplication(
    realpath(__DIR__.'/../')
);

That’s it. We’re now using our custom Application everywhere through the site.

Override (extend) your methods

So, if our goal is to override the functionality in Application that provides the location for the storage directory, the final step is to find that functionality and override it.

Thankfully again, a quick glance through the IlluminateFoundationApplication class makes that very clear: there’s a method named storagePath:

    /**
     * Get the path to the storage directory.
     *
     * @return string
     */
    public function storagePath()
    {
        return $this->basePath.'/storage';
    }

… so, let’s do our business. In our custom Application, let’s override that method:

<?php namespace Confomo;

class Application extends IlluminateFoundationApplication
{
    /**
     * Get the path to the storage directory.
     *
     * @return string
     */
    public function storagePath()
    {
        return $this->basePath.'/OMGstorage';
    }
}

… and done. We’ve now just customized this path. And, of course, we can use this same set of steps to extend anything else that the Application class provides to Laravel.

Conclado

That’s it! I hope this gives you the freedom and power to take more control of your Laravel-based web sites, and also the encouragement to go look around the core even more to learn how everything works.



Source link https://mattstauffer.com/blog/extending--application

LEAVE A REPLY

Please enter your comment!
Please enter your name here