I was just going through the laravel documentation HERE and came across the following peice of code ::
<?php
namespace App\Providers;
use Riak\Connection;
use Illuminate\Support\ServiceProvider;
class RiakServiceProvider extends ServiceProvider
{
/**
* Register bindings in the container.
*
* #return void
*/
public function register()
{
$this->app->singleton('Riak\Contracts\Connection', function ($app) {
return new Connection(config('riak'));
});
}
}
I am new to use in php , just learnt how it functions a few days ago , now does use , when used with a framework like laravel, where one class can be in a directory totally different from another , need to specify the directory structure too ?
I.E. can directory structure impact the way use is used ?
The use statement in PHP (when used outside of a class) is used to import a class from another namespace. Namespaces and folder structure do not necessarily correspond, but it is generally pretty close.
The autoloader used by Laravel, and most other modern PHP applications is part of the Composer package manager. Composer in turn supports multiple namespace standards, most notably PSR-0 and its successor, PSR-4.
In a composer.json file, you'll generally specify a namespace to autoload, and a base directory like so:
{
"autoload": {
"psr-4": {
"My\\Namespace\\": "src"
}
}
}
Any classes in the src/ directory should be in the My\Namespace directory. Classes in src/Model should have the namespace My\Namespace\Model and so on.
What a lot of PHP libraries use nowadays is called an autoloader which may mirror the directory structure, but does not necessarily have to.
Related
First off, the issue/question arose with Laravel 5.6 and PHP 7.4.10. I know that 'magic strings' for controller calls have been deprecated as of recent Laravel versions, but I'm interested in the underlying infrastructure in this question.
PREREQUISITES
Suppose I have two folders: project and core.
project contains a freshly installed laravel project;
core contains some package-like structure of namespaces and classes (not actually a package in the laravel sense), which is being autoloaded by the project.
For a minimal working example, you can see the last commit of the repository I published about this. I'm going to post the main files' contents here as well, but you can actually reproduce and play around with the sample projects yourself.
Basically the concept is pretty standard, much like a package: I want to have some reusable logic inside of my core with some default implementations. In the project I may or may not overwrite some of the functions, but for the sake of the question's simplicity, my core only defines a Fruit module (just a folder with a namespace) containig three files:
fruit_routes.php
<?php
Route::get('/pear', 'FruitController#pear');
Route::get('/apple', 'FruitController#apple');
FruitController (This is where the question is focused)
<?php
namespace CORE\Fruit;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class FruitController extends Controller
{
public function pear()
{
//if we call the action '\CORE\Fruit\FruitController#apple' instead, it works :)
return redirect()->action('FruitController#apple', ['message' => "No pears available! :( "]);
}
public function apple(Request $request)
{
return $request->message . "There you have an apple!";
}
}
FruitServiceProvider
<?php
namespace CORE\Fruit;
use Illuminate\Support\ServiceProvider;
class FruitServiceProvider extends ServiceProvider
{
public function register()
{
/*
* Map routes from our Fruit module to the controller's namespace
*/
$this->app->router->namespace('CORE\Fruit')->group(__DIR__."/fruit_routes.php");
}
}
And then in the project I simply include the following two lines:
composer.json
{
//..
"autoload":
//...
"psr-4": {
"App\\": "app/",
"CORE\\" : "../core"
}
},
}
config/app.php in $providers array
/*
* Package Service Providers...
*/
CORE\Fruit\FruitServiceProvider::class,
Again, for the full sample structure and contents, refer to the MWE repo.
THE QUESTION
Although the namespace for the controller classes has been explicitly declared from the FruitServiceProvider's register() method for the fruit_routes.php file, Laravel still fails to recognize that same namespace when using rediret()->action() from within those same controllers.
In the given FruitController you can see:
return redirect()->action('FruitController#apple');
and this will fail with Action App\Http\Controllers\FruitController#apple not defined.
As you can see, Laravel still searches for the controller inside the current project's default controller namespace (in this case: App\Http\Controllers)
Fortunately, passing the fully qualified name of the controller solves the issue:
return redirect()->action([self::class, 'apple']);
//Or alternativelly, but really clumsy:
//return redirect()->action('\Core\Fruit\FruitController#apple'); //notice the slash at the beginning
I have the suspicion that I must somehow also inform the redirect() helper (and actually, the underlying Redirect facade) that I want it to reference the controllers inside of my CORE\Fruit namespace whenever called from within that namespace... Or what would be the right approach? Is that desired behavior and am I missing something? And again, as mentioned in the beginning, I know that 'magic strings' are not the best practice and the most beloved feature of Laravel, but I really want to understand how things work in this scenario.
I also found this issue on github with a realted topic, but no answer there as well. As for people who are about to comment 'just avoid using magic strings', I'm stuck with a project I inherited and rewriting all of the core's magic string controller references is really not an option I would love to embrace.
Any insight is appreaciated! Many many thanks in advance!
So subject is the question. Yes, I've searched this forum and googled too. All I've got - useless Symfony docs and casts, some general advises, cli-s and nothing case specific. Maybe yahoo or duckduck could help better?
Everyone is talking about bundles, about how it is important to create them, probably because under the hood Symfony is pushing users away from custom libraries, but no one is actually explains how to start using a bundle - how to start calling its methods.
No, my library is not a composer or whatever package. No, library methods do not return Response objects. No, I am not dealing with composer or recompilations or cli (I use Composercat). No, I will not put library to github or packagist to load it via composer or whatever because it is private library.
Sorry about emotional off-topic.
About the case: I've put my library into the folder
src/lib/MyLibrary.php
I suspect that library class is autoloaded, because if I do not extend Controller with it (if I declare class MyLibrary instead of class MyLibrary extends Controller) - Symfony spits "class name in use" error.
So question: in my controller how to call library method?
$this->get('MyLibrary') doesn't work.
echo print_r($this) doesn't show MyLibrary in this registry too.
Looks like library file is loaded but not registered and/or instantiated. If it is so, then where to point Symfony to register it?
So most of this question is really about how php manages classes. Not so much about Symfony. But that's okay.
To start with it would be best to move project/src/lib to just project/lib. Symfony has some scanning stuff going on in the src directory and you really don't want to have your library mixed up in it.
So:
# lib/MyLibrary.php
namespace Roman;
class MyLibrary
{
public function hello()
{
return 'hello';
}
}
Notice that I added a namespace (Roman) just to distinguish your code from Symfony's.
Now you need to tweak composer.json in order to allow php to autoload your classes:
"autoload": {
"psr-4": {
"App\\": "src/",
"Roman\\": "lib/"
}
},
After adding the Roman line, run "composer dump-autoload" to regenerate the autoload files.
After that, it's just a question of using regular php inside of your application:
# src/Controller/DefaultController.php
namespace App\Controller;
use Roman\MyLibrary;
use Symfony\Component\HttpFoundation\Response;
class DefaultController
{
public function index()
{
$myLibrary = new MyLibrary();
$hello = $myLibrary->hello();
return new Response($hello);
}
}
And that should get your started.
I am trying to change an autoloading system that I've written before.
I'm using composer and at the moment I'm autoloading just one library with class map.
"autoload": {
"classmap": ["libs/"]
}
I want to add a psr-4 loader for the rest of the files and to be able to call the files under libs without namespaces and without "use" them' kind of like aliases in laravel. This is what I'm trying to do:
"autoload": {
"classmap": ["libs/"],
"psr-4": {
"App\\": ""
}
}
So eventually if in "libs" I have the Session class I'm calling it as:
Session::get('anything')
but now after trying to add the psr-4 and calling it from within a namespaced class
namespace App\models;
Class User{
function get(){
return Session::get('anything');
}
}
It won't work anymore because it looks for session within the user's namespace.
I know there are many frameworks which implements it out of the box with aliases.., it's just that this project is kinda old and I'm trying to organize it a bit and get rid of all the requires anywhere - at the moment each model has to be required.
I want to add a psr-4 loader for the rest of the files and to be able to call the files under libs without namespaces and without "use" them' kind of like aliases in laravel.
You can't use the classes without either adding use or adding the fully qualified namespace path starting with the backslash \. This has nothing to do with the way you load these classes, but is a basic requirement of PHP itself - so there is no way around it no matter how you'd like to design your autoloading.
As was commented, adding a backslash works, but this is the required minimum:
namespace App\models;
Class User{
function get(){
return \Session::get('anything');
}
}
I've ended up writing another class that aliasing any classses that i want so i will be able to call them out of the box.
you can see it here:
https://github.com/shahafan/SAmvc-App/blob/master/Config/Aliases.php
basically i'm just using the php class_alias function so i can load all the classes that i want before using them.
i think laravel does it the same way.
I have a Symfony project to which I added some non-symfony php files containing various classes. But for some reason the classes are not loaded when loading the website, even though the IDE sees them properly.
So, I have a class that needs other classes:
namespace rootspace\FrontBundle\Controller;
use rootspace\FrontBundle\Networks\TwitterOAuth;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
class TwitterController extends Controller
{
public function connectAction(){
// The TwitterOAuth instance
$connection = new TwitterOAuth('abc', '123');
}
}
And then the class which fails to load (that needs yet another file)
namespace rootspace\FrontBundle\Networks;
/* Load OAuth lib. You can find it at http://oauth.net */
//require_once('OAuth.php'); -- should this be commented out?
/**
* Twitter OAuth class
*/
class TwitterOAuth {
/* Contains the last HTTP status code returned. */
}
Lastly, the third file
namespace rootspace\FrontBundle\Networks;
use Symfony\Component\Config\Definition\Exception\Exception;
class OAuthConsumer
{
public $key;
public $secret;
}
(...)
I assume the actual filenames don't matter, right? Nor their structure? PhpStorm sees all the classes properly, I can right-click through them, but it fails when deployed.
Thanks for help
Edit - the whole error message says
Attempted to load class "TwitterOAuth" from namespace "rootspace\FrontBundle\Networks" in D:\Dropbox\project\src\rootspace\FrontBundle\Controller\TwitterController.php line 15. Do you need to "use" it from another namespace?
This is because Symfony's autoloader follows PSR standards (PSR-0, PSR-4) which says that fully qualified (with namespace) class name translates to file location and name. So in fact file names does matter.
So in your case rootspace\FrontBundle\Networks\TwitterOAuth class should be located in rootspace/FrontBundle/Networks directory in file called TwitterOAuth.php
If classes you are using does not follow PSR standards you can also register them manually in app/autoloader.php file
Check these for more info:
How can I add a namespace to Symfony 2.1?:
How to autoload class
And check this answer
I forgot to add a .php extension to my filename
I'm running PHPUnit using a bootstrap file for autoloading classes (generated by composer).
All my tests load up classes just fine, but for two of my tests, I made a "base" test class which extends \PHPUnit\Framework\TestCase (similar to PHPUnit_Framework_TestCase before PHPUnit7), and then two test classes that extend the base class, similar structure to the following example code:
abstract class BaseTest extends \PHPUnit\Framework\TestCase
{
abstract function setUp();
protected function getCommonTestVariables()
{
// ...
}
protected function runCommonTests()
{
// ...
}
}
class BlahBlahTest extends BaseTest
{
public function setUp()
{
$variables=$this->getCommonTestVariables();
//etc...
}
public function testThings()
{
$this->runCommonTests();
}
}
Whenever I run this, PHPUnit gives an error:
Fatal error: Class 'BaseTest' not found in BlahBlahTest.php on line 13
I've checked filenames, locations, namespaces and everything seems to be in order. Any help would be appreciated to get to the bottom of this
I ran into the same problem and if you are not too familiar with the inner workings of both PHPUnit and Composer this can indeed seem perplexing.
PHPunit does not use use the Composer autoloader to find any of your test classes. It just scans any directory you give it and operates on one file at a time.
Hence it does not know about any other class than the one in the file it is currently operating on. That is where the bootstrap file comes into play.
If you want to use the Composer Autoloader to load other test classes, you need to tell it where it can find these test classes (and, optionally, in which namespace).
There are two ways to do this:
Add an autoload-dev section to your composer.json or
Add the test directory to the Composer Autoloader
Use autoload-dev
The autoload-dev sections allows you to define autoload rules for development purposes.
Quoting directly from the manual:
Classes needed to run the test suite should not be included in the
main autoload rules to avoid polluting the autoloader in production
and when other people use your package as a dependency.
Therefore, it is a good idea to rely on a dedicated path for your unit
tests and to add it within the autoload-dev section.
Example:
{
"autoload": {
"psr-4": { "MyLibrary\\": "src/" }
},
"autoload-dev": {
"psr-4": { "MyLibrary\\Tests\\": "tests/" }
}
}
Add to the Composer Autoloader
An alternative would be to get the Composer Autoloader and add your testing namespace (if you have any) and the directory where your tests live. How to do this, as described in the manual (at the bottom of the autoloading section in "Basic Usage") is :
$loader = require('/path/to/vendor/autoload.php');
$loader->add('Test\\', __DIR__ . '/Tests');
If your tests use namespaces that mirror the test directory and you still run into trouble, you can try omitting the prefix by replacing the first parameter ('Test\\') with ''.
If you want further insight into how all of this works you should take a look at the Composer ClassLoader class, especially the add() and findFile() methods.
For me the solution was much simpler.
I changed the capital letter of Test to test at the end of the file and the class name
BaseSomethingtest.php
<?php
namespace Something\Tests\Sub1\Sub2;
class BaseSomethingtest
{
}
I just put a word at the end of my base class. As far as it
didn't finish with Test, phpunit didn't call it
BaseSomethingTestCase.php
<?php
namespace Something\Tests\Sub1\Sub2;
class BaseSomethingTestCase
{
}
I'm not sure if you still need a solution, but this worked for me:
Non-testable base class extending PHPUnit_Framework_TestCase
In PHP 7.0+ extends PHPUnit_Framework_TestCasechanged to extends \PHPUnit\Framework\TestCase, try this one.