laraveloverridinglaravel-6modularization

How to override the resourcePath() function defined in Illuminate/Foundation/Application.php


I am modularizing laravel. I have decided to move all the default routes, controllers, resources, etc.. to /app/Modules/Pub. For the most part this has worked well. However I would like to change the default resources path of the application. Unfortunately this doesn't seem to be (easily) configurable.

So... using grep I was able to track down the resource_path() function to /var/www/sigma/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php

I think it's possible to override this function somewhere but this seems like a subpar hack as this function consists simply of:

app()->resourcePath($path)

Again using grep I found out that this function is to be found in /var/www/sigma/vendor/laravel/framework/src/Illuminate/Foundation/Application.php

This seems to be the thing to change since it does not reference any configuration value, rather the value is hard coded:

return $this->basePath.DIRECTORY_SEPARATOR.'resources'.($path ? DIRECTORY_SEPARATOR.$path : $path);

But I think it's safe to assume it's pretty foolish to change anything under the vendor folder manually. Obviously I need to override this function somewhere. I am unclear where and how to do this


Solution

  • Create a new Application class which extends the \Illuminate\Foundation\Application:

    <?php
    
    namespace <YOUR NAMESPACE HERE>;
    
    class ApplicationCustom extends \Illuminate\Foundation\Application
    {
        public function __construct()
        {
            parent::__construct();
        }
        /**
         * Get the path to the resources directory.
         *
         * @param  string  $path
         * @return string
         */
        public function resourcePath($path = '')
        {
            // Implement the custom method
        }
    }
    

    Now, just change your bootstrap/app.php file to use the custom class:

    $app = new YOUR_NAMESPACE\ApplicationCustom(
        $_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
    );
    
    

    Hope it helps.