PHP use namespace class inside method in a class of another namespace - php

Is it possible in some way to instantiate a class inside a namespace, in a method in another class inside another namespace? And with the requested class instantiated from a variable?
Example:
Class to be loaded from loader-class:
namespace application/pages;
class loader
{
private function __construct()
{
echo 'Class loaded...';
}
}
Loader-class:
namespace system/loader;
class loader
{
private $vars;
private function __construct($vars)
{
$this->vars = $vars;
}
private function load_class()
{
require(CLASSES . $this->vars['namespace'] . '/' . $this->vars['class'] . ".php");
use $this->vars['namespace'];
return new \$this->vars['namespace']\$this->vars['class']();
}
}
Sorry for the bit confusing formulation, but i couldn't think of better way to ask the question.
Thanks.

This is the general way to load in namespaces:
http://www.php.net/manual/en/function.spl-autoload.php
However there is a more popular way of doing it using Composer.
Download composer.phar and inside your project directory run: php composer.phar init
Following the interactions.
In your project root, create a src directory then add this to your composer.json file which generated: "autoload": { "psr-0": { "": "src/" } }
Your composer.json file should now look like this:
{
"name": "acme/sample",
"authors": [
{
"name": "Person",
"email": "person#example.com"
}
],
"minimum-stability": "dev",
"autoload": {
"psr-0": { "": "src/" }
},
"require": {
}
}
Run: php composer.phar install, which will generate a vendors directory and an autoload script.
Create your primary load php file and include the autoload.php file inside.
Now, your namespaces inside the src directory and any imported libraries in vendor, will be exposed to your application.
Checkout symfony/symfony-standard to see a full framework example.

Related

Configure composer to use class names with prefixes

I have a folder structure like this:
Root-Folder/backend/user/class-user.php
Root-Folder/backend/profile/class-profile.php
Root-Folder/backend/login.php
Sample class-user.php content:
namespace myapp\user;
class User{
....
}
In my composer.json:
...
"autoload": {
"psr-4": {
"myapp\\": "backend/"
}
},
...
But this way the files are not included because they have a class- prefix in the file name. If I change the file names to user.php and profile.php, they work.
How can I configure composer to include class-user.php too?
PSR-4 requires classes names to be the same as file name that contains it.
In this case you need to use "classmap" directive instead of PSR-4
https://getcomposer.org/doc/04-schema.md#classmap
{
"autoload": {
"classmap": ["backend"]
}
}

how to use a class in other class phpunit?

hello I am trying to organize my classes in the composer-phpunit format, my classes already work interlacing them with require but I would like to have my code by folders and not all the files in the src folder my structure is the following
project structure
I thought that adding two namespaces in the psr-4 attribute of the composer file would work this is the structure of my composer file
{
"name": "ramirogg/p4wsnc",
"repositories": [
{
"type":"vcs",
"url":"https://github.com/r4m1r0gg/PIEZAS_4_WEBSITES_NEW_CONCEPT"
}
],
"description": "p4wsnc library",
"type": "library",
"license": "MIT",
"minimum-stability": "dev",
"autoload": {
"psr-4": {
"p4wsncbase\\": "src/clases_base/",
"p4wsnctobase\\": "src/clases_directas_ala_base/"
},
"files": [
"src/helpers.php"
]
},
"require-dev": {
"phpunit/phpunit": "^9.5#dev"
}
}
This is the head class and this is how I defined the namespace
<?php
namespace p4wsncbase;
class Head {
//here is all my code if you need to see it let me know
}
this is the sethead class and this is how i call the head class
<?php
namespace p4wsnctobase;
use p4wsncbase\Head;
class SetHead {}
in the same way I do it for the other classes I have an even class for each class within the classes_base folder, for example for the head class I have the sethead class for the body class I have the setbody class and for the tag class I have the settag class the classes that start with set are in the folder classes_directas_ala_base
finally this is how I call the classes sethead, setbody and settag in the index
<?php
require __DIR__ . '/vendor/autoload.php';
use p4wsnctobase\SetHead;
use p4wsnctobase\SetBody;
use p4wsnctobase\SetTag;
I would like to thank you forever, I really would like to maintain this structure, thank you very much in advance

Composer psr-4 autoload issue

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.

How to use __autoload function when use composer load

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.

Symfony not finding a custom class

In my folder "/Vendor/User/Admin" I created a new custom class (Adminuser.php)
namespace \User\Admin;
class Adminuser {
public $username;
public $password;
}
Now Im trying to use it in a controller:
namespace Section\AdminBundle\Controller;
use \User\Admin;
class DefaultController extends Controller
{
public function indexAction()
{
$AdminUser = new \User\Admin\Adminuser(); // CLASS NOT FOUND!!
.......
Why is this happening?, the namespace is wrong? (I tried a few options..)
Im very begginer with Symfony, sorry.
You have 2 main issues.
The First
When declaring a namespace you should not start with a \
namespace \User\Admin;
Should just be:
namespace User\Admin;
The Second
If you want those classes to live in your Vendors Dir then you need to make sure the class is being autoloaded by symfony correctly. To do this we will use composer.
In your composer.json you will want to change this section from:
"autoload": {
"psr-0": { "": "src/" }
},
TO:
"autoload": {
"psr-0": { "": "src/" },
"psr-0": { "": "vendor/User/Admin" }
},
Then composer will add classes under that folder to the available namespaces and you will be able to access it as expected.
just remove the first "\" in the namespace, as the comments said. So the first file is:
namespace User\Admin;
class Adminuser {
public $username;
public $password;
}
if the problem persist check your autoloading configuration, maybe the right way would be using src dir to develop your code, not vendor :S

Categories