PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, February 12, 2022

[FIXED] Use Models / Controllers from a sub directory in new project

 February 12, 2022     laravel, php     No comments   

Issue

So I've been asked to create a new project in Laravel (5.4). The project will need to load in a "platform" which is also built in Laravel 5.4 and contains already written controllers and models.

I am currently autoloading the platform in composer as so :

"psr-4": {
            "App\\": "app/",
            "Frontend\\": "app/Modules/Frontend/",
            "Admin\\": "app/Modules/Admin/",
            "Platform\\": "../platform/Modules/"
        }

I have a routes file with the following in it :

Route::get('/', 'HomeController@index')->name('home');

Then inside of my HomeController, I'm trying to load the platforms' HomeController.

use Platform\Modules\Frontend\Controllers\HomeController as HC;

I am then presented with the error

Class 'Platform\Modules\Frontend\Controllers\HomeController' not found

Is this at all possible to do, wise to do? I'm open to any form of suggestions.


Solution

I have managed to mimic your situation in 2 PHP hello world projects.

The problem here is that your 2 projects are using the same namespace App and when you try to autoload the 2nd project into the namespace Platform, you get Class not found error. This is because your PSR-4 namespace for Platform doesn't correspond the namespace in your 2nd project.

App\Modules\Frontend\Controllers is never Platform\Modules\Frontend\Controllers. Those are totally 2 different namespaces.

Hopefully, there's a solution for this by providing an array of paths to the common namespace in both projects.

        "psr-4": {
            "App\\": ["app/", "../platform/Modules/"],
            "Frontend\\": "app/Modules/Frontend/",
            "Admin\\": "app/Modules/Admin/"
        }

In your HomeController, load your controller like this:

use App\Modules\Frontend\Controllers as HC;

Always double check running the command below if you get Class not found error:

composer dump-autoload


Answered By - parse
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing