app/Core
contollers
This is my website structure to put the main class, I user composer psr-4 rule to import class under app/Core folder.
composer.json
{
"autoload": {
"psr-4": {
"Core\\": ["app/Core"]
}
}
}
index.php
<?php
include 'vendor/autoload.php';
new Core/Api; // it's work
It works fine, but I want to autoload class under controllers folder without use namespace, so I use __autoload function like:
index.php
<?php
include 'vendor/autoload.php';
function __autoload($class_name) {
include 'controllers/' . $class_name . '.php';
}
new Test // Fatal error: Class 'test'
If I remove include 'vendor/autoload.php'; it will work, so I think the code is correct, I know I can use classmap in composer.json, but it need to dump-autoload everytime I add a new class, how to deal with the conflict?
You do not have to use your own implementation of autoloading. You could use composer autoloading for all classes.
{
"autoload": {
"psr-0": { "": "src/" }
}
}
https://getcomposer.org/doc/04-schema.md#psr-0
Or, you could create class map
https://getcomposer.org/doc/04-schema.md#classmap
p.s. indeed, you could use empty namespace with psr-4.
Related
I have problem with autoloading with composer when i use psr-4 autoloading it doesn't work and give me error.
I tried:
$ composer dump-autoload
and a lot of other thing but it doesn't work without
require one;
error:
You are now a master builder, that knows how to autoload with a
classmap!
Fatal error: Uncaught Error: Class 'VegithemesLibraryGreeting' not
found in /home/vaclav/Server/vssk/VSSK/project/aldemo/index.php:10
Stack trace: #0 {main} thrown in
/home/vaclav/Server/vssk/VSSK/project/aldemo/index.php on line 10
composer.json:
{
"autoload": {
"files": ["mylibrary/functions.php"],
"classmap": [
"classmap"
],
"psr-4": {
"one\\": "src/"
}
}
}
greeting.php (file with class to load):
<?php
namespace one;
Class Greeting
{
public function hi()
{
return "We got you covered";
}
}
index.php file:
<?php
require 'vendor/autoload.php';
echo lego();
$cm = new Cmautoload;
echo $cm->classmap();
$vt = new oneGreeting;
echo $vt->hi();
It is generally good practice to capitalize the first letter of a class name. It also adheres with the rules of PSR-1.
Change your composer.json file to look like this:
{
"autoload": {
"files": [
"mylibrary/functions.php"
],
"classmap": [
"classmap"
],
"psr-4": {
"One\\": "src/"
}
}
}
Now, in your index file. We are going to import the autoloader. To do this simply require it:
require 'vendor/autoload.php';
Now that you have included the autoloader, go into every class and set the namespace.
The classes in your src/ == namespace One;
Check your classes in src/ and make sure they are all namespaced. Meaning that they should all have the following line of code at the top:
namespace One;
As mentioned before, update your file names to Foo.php and class names to
class Foo to adhere to PSR. (This is not required but highly recommended and standard procedure.)
To use one of your classes you would say use One\Greeting;
$greeting = new Greeting();
echo $greeting->hi(); //"We got you covered"
I found the problem, there was missing:
use One\Greeting;
In a lot of tutorials there isn't a word about it.
Another relevant detail about this is the namespace must match with the folder structure.
If not it will throw the warning.
In my case the filename was
src/One/GreetingClass.php
but the class name was in lowercase, causing this error:
class Greetingclass {
Changing the class declaration as GreetingClass fixed the issue.
I'm developing a REST API with Silex and I'm facing a problem regarding autoloading of my custom librairy. It looks like Composer's autoload is not including it, because when I include it myself it works.
# The autoload section in composer.json
# Tried with :
# "Oc\\": "src/Oc"
# "Oc\\": "src/"
# "": "src/"
"autoload": {
"psr-4": {
"Oc\\": "src/"
}
}
<?php
// api/index.php <-- public-facing API
require_once __DIR__.'/../vendor/autoload.php';
$app = require __DIR__.'/../src/app.php';
require __DIR__.'/../src/routes.php'; // <--
$app->run();
<?php
// src/routes.php
// When uncommented, it works!
//include('Oc/ParseImport.php');
use Symfony\Component\HttpFoundation\Response;
use Oc\ParseImport;
$app->get('/hello', function () use ($app) {
return new Response(Oc\ParseImport(), 200);
});
<?php
// src/Oc/ParseImport.php
namespace Oc {
function ParseImport() {
return 'foobar!';
}
}
I run composer dumpautoload after each composer.json manipulation, and I do see the line 'Oc\\' => array($baseDir . '/src/Oc') (or anything I tried) in vendor/composer/autoload_psr4.php.
I can't figure out what is wrong.
Almost everything you did was correct.
When trying to autoload classes in a namespace, given that a class is named Oc\Foo and is located in the file src/Oc/Foo.php, the correct autoloading would be "PSR-4": { "Oc\\": "src/Oc" }.
However, you do not have a class. You have a function. And functions cannot be autoloaded by PHP until now. It has been proposed more than once (the one proposal I found easily is https://wiki.php.net/rfc/function_autoloading), but until now this feature hasn't been implemented.
Your alternative solutions:
Move the function into a static method of a class. Classes can be autoloaded.
Include the function definition as "files" autoloading: "files": ["src/Oc/ParseImport.php"] Note that this approach will always include that file even if it isn't being used - but there is no other way to include functions in PHP.
As illustration see how Guzzle did it:
Autoloading in composer.json
Conditional include of functions based on function_exists
Function definition
Here is my folder structure:
Classes
- CronJobs
- Weather
- WeatherSite.php
I want to load WeatherSite class from my script. Im using composer with autoload:
$loader = include(LIBRARY .'autoload.php');
$loader->add('Classes\Weather',CLASSES .'cronjobs/weather');
$weather = new Classes\Weather\WeatherSite();
Im assuming the above code is adding the namespace and the path that namespace resolves to. But when the page loads I always get this error:
Fatal error: Class 'Classes\Weather\WeatherSite' not found
Here is my WeatherSite.php file:
namespace Classes\Weather;
class WeatherSite {
public function __construct()
{
}
public function findWeatherSites()
{
}
}
What am I doing wrong?
You actually don't need custom autoloader, you can use PSR-4.
Update your autoload section in composer.json:
"autoload": {
"psr-4": {
"Classes\\Weather\\": "Classes/CronJobs/Weather"
}
}
To explain: it's {"Namespace\\\": "directory to be found in"}
Don't forget to run composer dump-autoload to update Composer cache.
Then you can use it like this:
include(LIBRARY .'autoload.php');
$weather = new Classes\Weather\WeatherSite();
I'm trying to split up a long file into smaller chunks, so I created an src folder, and am trying to reference it from the main Extension.php file (which loads and works fine, by the way).
So, I add the src folder to the psr-4 autoloading array:
"psr-4": {
"Bolt\\Extension\\AndyJessop\\SurveyMonkey\\": [
"",
"src/"
]
}
I create the Test.php file inside src:
<?php
namespace Bolt\Extension\AndyJessop\SurveyMonkey;
class Test
{
public function test() {
return 'success';
}
}
In the Extension.php file (which is under the same namespace), I have this function that is called:
use Bolt\Extension\AndyJessop\SurveyMonkey\Test;
public function testing(){
return Test::test();
}
But I get the following error:
Error: Class 'Bolt\Extension\AndyJessop\SurveyMonkey\Test' not found
File: extensions/local/andyjessop/surveymonkey/Extension.php
First, either run composer update or composer dump-autoload to generate the autoload system.
Next, make sure that you include (require_once is preferable) the autoload at the top of your entrypoint(s):
require_once __DIR__ . '/path/to/vendor/autoload.php';
N.B.: if you have PHP 5.3 or lower, replace __DIR__ with dirname(__FILE__).
I have trouble adding my own namespaces to composer with PSR-0. I have read this and this but I still can't make it work
composer.json
{
"require": {
"klein/klein": "2.0.x",
"doctrine/orm": "2.4.4"
},
"autoload": {
"psr-0": {
"mynamespace": "src/"
}
}
}
The src folder is placed inside the same directory as composer.json
The src directory has the following structure
src
└── mynamespace
├── Keys.php
Keys.php
<?php
namespace mynamespace\Keys;
define ("API_KEY", "XXXXXXXXXXXX");
?>
index.php
use Klein\Klein;
use mynamespace\Keys;
require_once __DIR__ . '/vendor/autoload.php';
$klein = new Klein(); // works
echo API_KEY; // Undefined constant
You can only load classes, interfaces and traits with autoloading.
Because all you do is add a use clause which does not do anything by itself with autoloading (i.e. it does not load something), and you do not use a class, nothing happens.
I recommend using class constants. They may be put into classes or interfaces:
namespace mynamespace;
interface Keys {
const API_KEY = 'XXXXXXXX';
}
use mynamespace/Keys;
echo Keys::API_KEY;