Reputation:
I'm working with Laravel framework.
I have a question regarding classes creation. To explain my question, i will give you an example:
class articleController extends Controller{
public function bla(){
$a = new MyNewClass($colorfulVariable);
$b = $a->createSomething(new MySecondNewClass());
}
}
Now, the classes MyNewClass
and MySecondNewClass
do not exist, I want to create them, use them in every controller I want, just like I use the Redirect or Request classes that Laravel
offers.
How can i create this classes? Make a new functions to use them in my laravel project?
Upvotes: 2
Views: 23681
Reputation: 1146
Laravel 5.* is autoloaded using PSR-4, within the app/ directory. You can see this in the composer.json file.
"autoload": {
"classmap": [
"database/seeds",
"database/factories"
],
"psr-4": {
"App\\": "app/"
}
},
Basically, you could create another directory within app, and then namespace your files in there as appropriate:
app/folder1/folder2/SomeClass.php.
Then, within your SomeClass.php, make sure you namespace it:
<?php namespace App\folder1\folder2;
class Someclass {}
Now, you can access this class using the namespace within your classes:
use App\folder1\folder2\SomeClass;
Upvotes: 4
Reputation: 6018
You don't have to do anything other than below things:
thats it. Mostly people follow convention and then create "Service" folder on App\ folder. It is good to create alien class into service folder which are other than laravel framework classes.
Upvotes: 0
Reputation: 163788
You can create your classes as usual, but don't forget to include them into composer.json
autoload section:
"autoload": {
"classmap": [
"App\MyClassesNamespace"
....
And then run composer dumpauto
command to rebuild autoloader file. If you'll not do this, you'll not be able to use your classes in your application.
Upvotes: 3
Reputation: 5935
you can just create those classes in your app folder (or in subfolder for example we create a Libraries folder with all the utilities). Just include a use App\YourClass; before using those classes and laravel will include the classes for you
Upvotes: 10