I was reading some tutorials on creating custom classes for Laravel. I followed instructions and did exactly what tutorials say:
Created new folder laravel/app/libraries/graphics/
Edited laravel/app/start/global.php where I added:
app_path().'/libraries/graphics',
Created new file in laravel/app/libraries/graphics/ named Image.php with this code:
<?php namespace graphics/Image;
class Image {
public static function hello() {
return 'Hello';
}
}
Used composer dump-autload command
Route::get('/' , function() { return Graphics\Image::hello(); } ); is returning error:
Use of undefined constant graphics - assumed 'graphics'
I also added "app/libraries/graphics/Image.php"line into composer.json autload section, which should not be neccessary. Why I am getting this error? Every tutorial shows the same procedure for this, but why it doesn't work?
Shouldn't your namespace just be graphics? The current file creates graphics\Image\Image. Try removing Image from your namespace.
<?php namespace graphics;
class Image {
public static function hello() {
return 'Hello';
}
}
Have you tried using artisan dump-autoload instead?
It will clear all of Laravel's compiled code.
See here: What are differences between "php artisan dump-autoload" and "composer dump-autoload"
You don't need to confusion for yourself. I'm resolve issue into Laravel 5. You don't need to add "app/libraries/graphics/Image.php"line into composer.json autload section because By default, app directory is namespaced under App and is autoloaded by Composer using the PSR-4 autoloading standard.
<?php
namespace App\libraries\graphics;
class Image {
public static function hello() {
return 'Hello';
}
}
and now use your Image Class from your route.
Route::get('graphics',function(){
echo \App\libraries\graphics\Image::hello();
});
Related
I have two controller file homecontroller and backendcontroller. What is the best way to create global function and access it from both files?
I found here Arian Acosta's answer helpful but I wonder if there is an easiest way. I would appreciate any suggestions.
Solution
One way to do this is to create a class and use its instance, this way you can not only access the object of the class within a controller, blade, or any other class as well.
AppHelper file
In you app folder create a folder named Helpers and within it create a file name AppHelper or any of your choice
<?php
namespace App\Helpers;
class AppHelper
{
public function bladeHelper($someValue)
{
return "increment $someValue";
}
public function startQueryLog()
{
\DB::enableQueryLog();
}
public function showQueries()
{
dd(\DB::getQueryLog());
}
public static function instance()
{
return new AppHelper();
}
}
Usage
In a controller
When in a controller you can call the various functions
public function index()
{
//some code
//need to debug query
\App\Helpers\AppHelper::instance()->startQueryLog();
//some code that executes queries
\App\Helpers\AppHelper::instance()->showQueries();
}
In a blade file
Say you were in a blade file, here is how you can call the app blade helper function
some html code
{{ \App\Helpers\AppHelper::instance()->bladeHelper($value) }}
and then some html code
Reduce the overhead of namespace (Optional)
You can also reduce the overhead of call the complete function namespace \App\Helpers by creating alias for the AppHelper class in config\app.php
'aliases' => [
....
'AppHelper' => App\Helpers\AppHelper::class
]
and in your controller or your blade file, you can directly call
\AppHelper::instance()->functioName();
Easy Solution:
Create a new Helpers folder in your app directory.
Create a php file named your_helper_function.php in that Helpers directory.
Add your function(s) inside your_helper_function.php
function your_function($parameters){
//function logic
}
function your_another_function($parameters){
//function logic
}
Add this file to the Files key of your composer.json like
"autoload": {
...
"files": [
"app/Helpers/your_helper_function.php"
]
...
}
Finally, regenerate composer autoload files. (Run this in your project directory)
composer dump-autoload
That's it! and now you can access your_function() or your_another_function() in any part of your Laravel project.
If you still have any confusion, check my blog post on how to do this:
How to Add a Global Function in Laravel Using Composer?
Updated:
Step 1
Add folder inside app folder
app->Helper
Step 2
add php Class inside Helper folder
Eg. Helper.php
Add namespace and class to the Helper.php
namespace App\Helper;
class Helper
{
}
Register this Helper.php into config/app.php file
'aliases' => [
....
'Helper' => App\Helper\Helper::class
]
Now, write all the functions inside Helper.php and it will be accessible everywhere.
How to access from Controller?
Step 1 - Add a namespace at top of the controller.
use App\Helper\Helper;
Step 2 - Call function - Assume there a getInformation() inside the Helper Class.
$information = Helper::getInformation()
In your Controller.php which extends BaseController, you can create a function like;
public function data($arr = false)
{
$data['foo'] = 'bar';
return array_merge($data,$arr);
}
And from any controller when you send a data to a view;
public function example()
{
$data['smthg'] = 'smthgelse';
return view('myView',$this->data($data));
}
The data in the the main controller can be accessed from all controllers and blades.
The Laravel Service Provider way
I've been using global function within Laravel for a while and I want to share how I do it. It's kind of a mix between 2 answers in this post : https://stackoverflow.com/a/44021966/5543999 and https://stackoverflow.com/a/44024328/5543999
This way will load a file within a ServiceProvider and register it within your Laravel app.
Where is the difference, the scope, it's always about the scope.
Composer //Autload whitin composer.json method
|
|--->Laravel App //My method
|
|--->Controller //Trait method
|--->Blade //Trait method
|--->Listener //Trait method
|--->...
This is a really simplist way to explain my point, all three methods will achieve the purpose of the "Global function". The Traits method will need you to declare use App\Helpers\Trait; or App\Helpers\Trait::function().
The composer and service provider are almost about the same. For me, they answer better to the question of what is a global function, because they don't require to declare them on each place you want to use them. You just use them function(). The main difference is how you prefer things.
How to
Create the functions file : App\Functions\GlobalFunctions.php
//App\Functions\GlobalFunctions.php
<?php
function first_function()
{
//function logic
}
function second_function()
{
//function logic
}
Create a ServiceProvider:
//Into the console
php artisan make:provider GlobalFunctionsServiceProvider
Open the new file App\Providers\GlobalFunctionsServiceProvider.php and edit the register method
//App\Providers\GlobalFunctionsServiceProvider.php
public function register()
{
require_once base_path().'/app/Functions/GlobalFunctions.php';
}
Register your provider into App\Config\App.php wihtin the providers
//App\Config\App.php
'providers' => [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
...
Illuminate\Validation\ValidationServiceProvider::class,
Illuminate\View\ViewServiceProvider::class,
App\Providers\GlobalFunctionsServiceProvider::class, //Add your service provider
Run some artisan's commands
//Into the console
php artisan clear-compiled
php artisan config:cache
Use your new global functions
//Use your function anywhere within your Laravel app
first_function();
second_function();
Laravel uses namespaces by default. So you need to follow the method described in that answer to setup a helper file.
Though in your case you want to access a method in different controllers. For this there's a simpler way. Add a method to you base controller app/Http/Controllers/Controller.php and you can access them in every other controller since they extend it.
// in app/Http/Controllers/Controller.php
protected function dummy()
{
return 'dummy';
}
// in homecontroller
$this->dummy();
There are a few ways, depending on the exact functionality you're trying to add.
1) Create a function inside Controller.php, and make all other controller extend that controller. You could somewhat compair this to the master.blade.php
2) Create a trait, a trait can do a lot for you, and keeping ur controllers clean. I personally love to use traits as it will look clean, keep my Controller.php from being a mess with tons of different lines of code.
Creating a global function
create a Helpers.php file under a folder, let's name it 'core'.
core
|
-- Helpers.php
namespace Helpers; // define Helper scope
if(!function_exists('html')) {
function html($string) {
// run some code
return $str;
}
}
In your composer.json
"autoload": {
"psr-4": {
},
"files": [
"core/Helpers.php"
]
}
in the file that you want to use it
// the " use " statement is not needed, core/Helpers is loaded on every page
if(condition_is_true) {
echo Helpers\html($string);die();
}
Remove the namespace in Helpers.php if you want to call your function without the need to prefix namespace. However I advise to leave it there.
Credit: https://dev.to/kingsconsult/how-to-create-laravel-8-helpers-function-global-function-d8n
By using composer.json and put the function containing file(globalhelper.php) to the autoload > files section, then run
composer dump-autoload
You can access the function inside the file(globalhelper.php) without having to calling the class name, just like using default php function.
I just started using CakePHP 3. I'm trying to get up and running but doing the simplest of things is proving to be a headache.
I have a class, MySimpleClass, in src/App/MySimpleClass.php
<?php
namespace MyApp\MyNamespace;
class MySimpleClass {
public function aSimpleFunction() {
return 1;
}
}
And in my controller:
<?php
namespace App\Controller;
use Cake\Controller\Controller;
use MyApp\MyNamespace\MySimpleClass;
class MyFirstController extends Controller {
public function display() {
$mySimpleClass = new MySimpleClass();
echo $mySimpleClass->aSimpleFunction();
}
}
But this always gives me:
Error in: ROOT/src/Controller/TestController.php, line 10 Class 'MyApp\MyNamespace\MySimpleClass' not found
I use bin/cake server to run the HTTP server
I added App::className('MyApp\MyNamespace\MySimpleClass'); to bootstrap.php to see if that'd make a difference but it doesn't.
I've run composer dump-autoload on several occasions.
I tried putting MySimpleClass into global namespace but it still gave me the error.
PHPStorm isn't giving me any syntax or naming errors.
You should place your controllers in:
src/Controller
and use:
namespace App\Controller;
Nevermind, I finally found the solution...
I just had to add src to the classmap in composer.json:
"autoload": {
"classmap": [
"src"
],
...,
}
Edit:
Instead of abusing classmap, I just moved my class files to a directory outside of src
If your class is in the file src/App/MySimpleClass.php, the namespace has to be App\App. The first App refers to the root namespace of every CakePHP 3.x application, the second App refers to the subdirectory within the src directory you put your class file into.
If the namespace of the class should be App\MyNamespace, your classfile has to be located in src/MyNamespace.
Also: according to the error message you quoted, your MyFirstController is in a file called TestController.php. Instead, it should be MyFirstController.php. I recommend giving https://book.cakephp.org/3.0/en/intro/conventions.html#file-and-class-name-conventions a read regarding this topic.
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've just set up a new Laravel 5 project. I included a Helpers.php in the /app directory. Here it is:
<?php namespace EP\Helpers;
class Helpers {
public static function sayHi()
{
return 'Hi';
}
}
And in the route I am doing:
Route::get('/', function(){
return EP\Helpers\Helpers::sayHi();
});
But when I hit that route I am getting the error:
Class 'EP\Helpers\Helpers' not found
The funny thing is, PHPStorm is able to auto detect the namespace. Anyone know why this would be happening?
I believe in your case the namespace would be:
<?php namespace EP;
The error I'm getting is that the controller doesn't exist even though I know it does, here's the code.
Route.php
Route::get('mdpay/template', array("uses" => "templateController#index"));
templateController.blade.php
class templateController extends BaseController {
public function index()
{
echo "made it";
}
}
Why might I be getting this error: Class TemplateController does not exist
================= UPDATE: ==================
Ok, so I've created the correct route, renamed my file, and corrected the class name and I'm still coming up with that error.
File Names:
templateController.php
// File Name: TemplateController.php
class TemplateController extends BaseController {
public function index()
{
// app/views/myView.blade.php
echo "hello";
}
}
My route is:
Route::get('mdpay/template', array("uses" => "TemplateController#index"));
Still receiving Controller Doesn't Exist error. All my other controllers (3 others) are working except this one.
If you are using the standard composer classmap autoloader you need to composer dumpautoload everytime you create a new file.
So to create a new controller with the standard composer setup given by Laravel:
Create a new file in app/controllers named TemplateController.php
Open up terminal and run composer dumpautoload
As previous users have said, only view files should end with .blade.php.
If you're using Laravel 8, add this line to your RouteServiceProvider.php (you can search it by using CTRL + P):
protected $namespace = 'App\Http\Controllers';
This solved the issue for me.
It should be:
// File Name: TemplateController.php
class TemplateController extends BaseController {
public function index()
{
// return "made it"; // or
// app/views/myView.blade.php
return View::make('myView');
}
}
Route for that:
Route::get('mdpay/template', array("uses" => "TemplateController#index"));
Use blade in a Blade view, i.e: myView.blade.php basically stored in app/views/ folder. Read more about blate template on Laravel website.
Controllers live in the app/controllers directory and should remain there unless you have your own namespaced structure.
The reason you're getting a Class TemplateController does not exist is because it doesn't, firstly, your class is called templateController and secondly, it exists as templateController.blade.php which wouldn't be loaded in this way.
Blade files are for views, and only views within app/views or a custom views directory should end with .blade.php.
Create the file app/controllers/TemplateController.php and add the following code to it.
class TemplateController extends BaseController {
public function index()
{
echo "made it";
}
}
Now on the command line, run the command composer dumpautoload and change you route declaration to:
Route::get('mdpay/template', array('uses' => 'TemplateController#index"));
Now it should all work.
In case you're using Laravel 9 and the error is like Illuminate\Contracts\Container\BindingResolutionException and Target class <controller name> does not exist. when trying php artisan route:list on terminal.
This is the setup that I do:
Add protected $namespace = 'App\\Http\\Controllers'; to RouteServiceProvider.php
Add 'namespace App\Http\Controllers;' to the controller file.
Do php artisan optimize on terminal
(Just to make sure the route already there) Do php artisan route:list again on terminal, and the controller route should be displayed.