I want to create my own class and use it inside my controller, but i don't know exactly how. I did the following:
I created a php file which contains my class in a sub-folder inside the App folder. the php file (class) is called JunkFunction and the sub-folder is called myClasses.
In my controller i insert this line of code on the top :
use App\myClasses\JunkFunction;
I create an object of the class as the following:
$function = new JunkFunction;
But this exception is thrown :
Class 'App\myClasses\JunkFunction' not found in D:\graduation
project\kh\app\Http\Controllers\UploadsController.php
There are two ways you can create a class in laravel (recommend)
1. Create a Model
This is the most recommended way to create a class in laravel.
command to create a model: php artisan make:model ModelName
then you can use it as a use App\ModelName;
2. As a helper
This is no recommend.This one only use when you need a function/class exist in anywhere in the project so you cannot create class/function in same names.
first create your class/function file and add it into the app folder.
Then open your composer.json file and add your file path inzide of autoload part
"autoload": {
"files": [
"app/YourFunction.php"
]
}
then run composer dump-autoload
and you are done.
namespace App\myClasses;
put the namespace on top of file
Related
In my new laravel app I've added two custom classes. One loads fine when I use it in the controller, but the other, which is in another folder, does not work.
The working class, which I will call Working is located in app\Classes, it has the namespace namespace App\Classes and in the controller I call it with use App\Classes\Working.
The non-working class, which I will call NonWorking is located in app\Classes\NonWorking. I've tried giving it the namespaces namespace App\Classes and namespace App\Classes\NonWorking. From the controller I've tried calling it with use App\Classes\NonWorking and use App\Classes\NonWorking\NonWorking, but I get the error Class 'App\Classes\NonWorking' not found or Class 'App\Classes\NonWorking\NonWorking' not found.
I've been able to get it to run correctly by moving the NonWorking class into the same folder as the Working class and setting the namespace as namespace App\Classes, but the NonWorking class is from another repo and should be in its own folder as it will not be the only one from another repo.
So, how do I get Laravel to understand where this class is?
Laravel uses the PSR-4 autoloading. What it means is basically your class should follow the folder structure.
So if you have classes in app/Classes, they should have the namespace App\Classes.
So the file app/Classes/Working.php will have at its top namespace App\Classes; and to import it in another file, you write in the other file use App\Classes\Working;
If you have a class inside app/Classes/SubFolder, it should have the namespace namespace App\Classes\SubFolder;
So here is a class AmazingClass in app/Classes/SubFolder/AmazingClass.php file:
// app/Classes/SubFolder/AmazingClass.php
namespace App\Classes\SubFolder;
class AmazingClass
{
//
}
Let's use AmazingClass in another class.
// Some file in another namespace
namespace App\My\Random;
use App\Classes\SubFolder\AmazingClass;
// Rest of the file
Plus: Whenever you add a new class and you can't use it, it's likely that it's not autoloaded. Run the command
composer dump-autoload
to re-autoload the classes.
to solve your issue just create your folders and classes in App folder and run command :
composer dump-autoload
and they load all classes you have created
I'm using a 3rd party extension like so:
(This is inside my controller)
require_once Yii::$app->basePath.'/vendor/campaignmonitor/createsend-php/csrest_subscribers.php';
$wrap = new CS_REST_Subscribers($list_id, $auth);
However, this is returning an error that CS_REST_subscribers class is not found.
How do I use this class correctly when the class is inside the file. Unfortunately this extension is older and is not namespaced.
You need to install it using composer with the following command
composer require "campaignmonitor/createsend-php" "6.0.0"
It uses the simplest way, i.e autoloads each class separately. we define the array of paths to the classes that we want to autoload in the composer.json file and if you see the vendor/campaignmonitor/createsend-php/composer.json file inside the package directory
"autoload": {
"classmap": [
"csrest_administrators.php",
"csrest_campaigns.php",
"csrest_clients.php",
"csrest_general.php",
"csrest_events.php",
"csrest_lists.php",
"csrest_people.php",
"csrest_segments.php",
"csrest_subscribers.php",
"csrest_templates.php",
"csrest_transactional_classicemail.php",
"csrest_transactional_smartemail.php",
"csrest_transactional_timeline.php"
]
}
so you won't need the include or require statement, you can directly call any class you want for instance adding the following lines inside your action or view
$authorize_url = CS_REST_General::authorize_url(
'1122',//'Client ID for your application',
'http://example.com/redirect-page',//Redirect URI for your application,
'ViewReports'//The permission level your application requires,
);
print_r($authorize_url);
prints the following
https://api.createsend.com/oauth?client_id=1122&redirect_uri=http%3A%2F%2Fexample.com%2Fredirect-page&scope=ViewReports
For knowledge base if you want to use a Third-party code that is not using autoloader or psr4 you can go through the Yii tutorial
I am trying to organise my app a bit better by putting models and controllers in subdirectories. I thought it didn't matter if they were in subdirectories as long as the namespace is correct, but now that I've moved them I'm getting a class not found error.
I have tried running composer dumpautoload several times, but it's still not working.
Here is my directory structure:
App
Models
Managers
EntryStructure.php
FieldManager.php
Controllers
EntryControllers.php
Since I have made the new directory Managers and moved those two models in there, When I reference the FieldManager class from EntryStructure, I get the not found error.
Code in EntryStructure.php:
namespace Pascall\ICMS\Models;
use Pascall\ICMS\Models\FieldManager;
class EntryStructure
{
function index(){
new FieldManager(); // class not found
}
}
Code in FieldManager.php:
namespace Pascall\ICMS\Models;
class FieldManager {
//
}
Why is it not finding the FieldManager class when it is explicitly referenced in the use statement and they share the same namespace?
Your use should be
use Pascall\ICMS\Models\Managers\FieldManager;
instead
use Pascall\ICMS\Models\FieldManager;
If your Models directory follow the PSR-4 specifications, the namespace in both of your classes should follow the class file path, so it should be:
namespace Pascall\ICMS\Models\Managers;
Then, in EntryStructure class you should use:
use Pascall\ICMS\Models\Managers\FieldManager;
I'm using the Laravel framework and have a directory of the following structure:
models
Statistic.php
presenters
StatisticPresenter.php
In my models/Statistic class, I'm trying to access a present method which calls a protected property which then references my presenter:
protected $presenter = 'presenters\StatisticPresenter';
public function present() {
return new $this->presenter($this);
}
Yet, this returns the error: Class 'presenters\StatisticPresenter' not found. I realize this is a namespacing error of some sort, and I've tried watching a few videos on how it works, but I simply can't wrap my head around it. I have already added my presenter folder to my composer.json file. For example, adding this to the top of my Statistic model does not work:
use presenters\StatisticPresenter;
How can I fix this?
Do the followings;
Mark your namespace in StatisticPresenter.php ? (at the top of file "namespace presenters;")
Add PSR-4 class map to your composer
{
"autoload": {
"psr-4": {
"presenters\\": "app/presenters/"
}
}
}
run "composer dump-autoload" once and you wont need to run this command again for the "presenters" namespace if you add new classes into "app/presenters/ folder"
Test your class with "use presenters/StatisticPresenter;"
If you can access your class you dont need to change your code your present() function will be valid
I have class in libraries/myclass.php and a function named myFunction. Also I try to call that function in my controller with the following code
$myclasobj=new libraries\Myclass();
$returnvalue=$myclasobj->myFunction($para);
results that class not found. I dont want it as a helper class and auto load this class. I just want to use as a simple class.I am using laravel 4.How can I obtain this?
Update
Thanks all of you for your great help.
As per #carousel,#Ohgodwhy I make it by namespacing (Actually before I don't know about it).
I make a directory under libraries named mylib and move my class (myclass.php) to it and after that I add namespace mylib; to the top of myclass.php.
And after that I add use mylib\Myclass; to my controller.
Finally I add these lines to composer.json
,
"psr-0": {
"mylib": "app/libraries"
},
After these things my class is working.Thanks to all for helping me
Every new class, in order to be used in Laravel, has to be linked to Application. It can be done in more then one way:
Through class map
With namespacing
By its path
In that sense there is no simple classes. All classes can become a part of Laravel Application flow, if they are referenced correctly with composer.
UPDATE TO MY ANSWER:
Here is a link to best resource that explaines facades.
Assuming that the file hasn't been loaded yet, the proper way to add your libraries/ directory to the classloader would be to modify your composer.json to add the directory to the autoloader.
autoload: {
classmap: [
"...",
"libraries/"
]
}
After that, you'll need to rebuild the autoloader, so in the home directory, go ahead and run this in your terminal:
$ php artisan dump-autoload -o
Also ensure that your class is actually contained inside a namespace, because using
new libraries\myClass();
Does not load "myClass" from the "libraries" folder. It would be helpful if you could add it to the original question.
Try doing this, it should solve your problem:
ClassLoader::addDirectories(array(
app_path().'/commands',
app_path().'/controllers',
app_path().'/models',
app_path().'/database/seeds',
app_path().'/classes', //we added this
));