PHP - Namespace isn't working properly - php

I am using xampp on windows 7 with php 5.6.24. I have problem with php Namespace.
My project direcotry look like this :
-project
+ config
- Framework
+ database
+ Expection
test.php
+ src
index.php
I have php file inside Framework/test.php and it contains the following code :
<?php
namespace Framework\Test;
echo " i Am in test.php class";
class Test{
public function __construct(){
echo "I m from test classs ";
}
public function test_method(){
echo " No";
}
}
In my root directory i have index.php, composer.json
My composer.json has autoload object
"autoload": {
"psr-4": {
"Framework\\": "Framework/"
},
"files": [
"src/Helpers/ArrayHelpers.php"
]
},
In my index.php, i have following code :
<?php
echo "<pre>";
require __DIR__ . '/vendor/autoload.php';
use Framework\Test;
$n = new Test;
print_r($n);
When i run index.php file on browser i get the responce :
i Am in test.php class;
Fatal error: Class 'Framework\Test' not found in
C:\xampp\htdocs\project\index.php on line 12
I don't know what i am doing wrong ? Is my namespace is wrong ? But i am getting echo from that file how ? why ? whats going wrong ? is my composer file wrong ?
Thanks in advance.

The namespace of the class Test is simply Framework, (because it is located in the Framework folder also) so try to change the Test.php as follow:
<?php
namespace Framework;
echo " i Am in test.php class";
class Test{
public function __construct(){
echo "I m from test classs ";
}
public function test_method(){
echo " No";
}
}
Hope this help

Related

Using session_start with Laravel OR using Laravel sessions across php files

I am using a Laravel app, and on one of my custom pages I have the following:
index1.php:
require_once __DIR__ . '/../../../vanguard/extra/auth.php';
$request->session()->forget('token1');
$request->session()->put('token1', $generate_token1);
$request->session()->keep(['token1']);
redirectTo('index2.php');
index2.php:
require_once __DIR__ . '/../../../vanguard/extra/auth.php';
$token1 = $request->session()->get('token1');
echo $token1;
It seem's the session isn't being saved across the pages. If I use all the code on one file it works. Any ideas?
I am using this because I can't seem to use session_start(); with Laravel.
Rather making a custom page make a class
define a class with a namespace
and use it in any of your pages inside any page like below.
Here are my steps :
The content for app/library/myFunctions.php is below :
<?php namespace App\library {
class myFunctions {
public function is_ok() {
return 'myFunction is OK';
}
}
}
?>
At resources/views/test.blade.php , I added :
<?php
$FmyFunctions1 = new myFunctions;
$is_ok = ($FmyFunctions1->is_ok());
?>
Then at composer.json within "autoload": I added :
"files": [
"app/library/myFunctions.php"
],
And within app\Http\Controllers\HomeController.php at public index() I add :
return view('test');

PSR4 not working?

Class not found, apparently. I've tried various things but nothing works.
Composer:
"autoload": {
"psr-4": {
"App\\": "application/"
}
}
File structure:
https://i.imgur.com/h9wOEqI.png
<?php
namespace App\Library\Classes;
defined('START') or exit('We couldn\'t process your request right now.');
class Application
{
private static $libraries = array();
public static function get($library) {
if (isset(self::$libraries[$library]) && isset(self::$classes[$library])) {
return self::$libraries[$library];
}
$fixedLibrary = str_replace('.', '/', $library);
$file = ROOT . '/application/library/classes/' . strtolower($fixedLibrary) . '.php';
self::$libraries[$library] = $library;
$declared = get_declared_classes();
$workingClass = end($declared);
self::$libraries[$library] = new $workingClass();
return self::$libraries[$library];
}
}
?>
Error is on this line:
Application::get('test')->test();
Yet, if I change it to this, it works:
include ROOT . '/application/Library/Application.php';
App\Library\Classes\Application::get('test')->test();
The PSR4 is not built-in part or PHP, you need an implementation of autoloader to use this standard such as provided by the Composer.
When you install or update depedencies, composer generates the relevant code of autoloading, but you can directly update it by the command dump-autoload, as #jibsteroos said. Next you should explicitly include the file vendor/autoload.php in the entry point of your application.
Also, error message says about class Application, but you should add the use statement at first:
use App\Library\Classes\Application;
Application::get('test')->test();
Or use the fully qualified class name (class name with namespace prefix):
\App\Library\Classes\Application::get('test')->test();

PHP - Extend classes using composer autoloader causes redeclare error

I'm just learning how to use composer for my own classes.
So I've this ditectory structure
I'm using PHP version 5.5.30 and Composer 1.1.0
Pdf
test.php
composer.json
vendor/
autoload.php
jarouche/
jarouche.php
jarouche2.php
So, I have
test.php
<?php
require_once('vendor/autoload.php');
use jarouche\jarouche2;
$teste = new jarouche2();
$teste->teste();
?>
jarouche.php
<?php
namespace jarouche;
class jarouche{
public function teste(){
echo 'jarouche';
}
}
?>
jarouche2.php
<?php
namespace jarouche;
class jarouche2 extends jarouche{
public function teste(){
echo 'jarouche2';
}
}
?>
composer.json
{
...
"autoload": {
...
"psr-4": {"jarouche\\": "vendor/jarouche"
}
}
But, when I run test.php I got this error "Fatal error: Cannot redeclare class jarouche\jarouche2 in C:\xampp\htdocs\Pdf\vendor\jarouche\jarouche2.php on line 6"
I've tried putting a if (!class_exists('MyClass')) in jarouche2.php, tried to update composer... nothing worked.
What's my mistake?
For some reason I did a composer self-update and now it's working!

Php psr-4 Class not Found Error using Composer

I'm trying to exercise MVC concepts with php on "wamp-server"
At local directory i have the index.php page for basic routing with alto-router package and a routes.php file:
<?php
$router->map('GET','/test', 'Acme\Controllers\PageController#test' ,'test');
composer.json file is:
{
"name": "eren/eren",
"authors": [
{
"name": "Eren Ardahan",
"email": "???#???.com"
}
],
"require": {
"filp/whoops": "^1.1",
"altorouter/altorouter": "1.1.0"
},
"autoload":{
"psr-4":{"Acme\\":"src/"}
}
}
PageController.php is
<?php namespace Acme\Controllers;
use Acme\Testing\Test;
class PageController
{
public function test(){
include(__DIR__ . "/../../views/test.php");
//---Deleted lines
$test = new Test;
$test -> test();
/---
}
}
The Test.php in the acme directory is:
<?php namespace Acme\Testing;
class Test{
public function test(){
echo "Working";
}
}
And The test.php in the view directory is above.And it works when i deleted the commented two lines in PageController.php
<?php
echo "TEST PAGE <br>";
But with this lines there is an error :
Class 'Acme\Testing\Test' not found..
As i said in the comment the problem is that the namespace is not correct.
I created this answer for people who might find this question in the future.
You have a directory called source wich has the namespace Acme. When u add another directory inside the source folder called acme the namespace will be:
Acme\acme
You will have to change the acme folder to Testing to get the right namespace.

Class Not Found / Cannot redeclare class

Hello i am having a weird issue when try including some classes in a file in my laravel project. This is the file:
<?php namespace Libraries\MPowerLib;
require("mpower/dependency_check.php");
set_include_path(get_include_path() . PATH_SEPARATOR . realpath(dirname(__FILE__)));
abstract class MPower {
const VERSION = "1.2.0";
}
if (strnatcmp(phpversion(),'5.3.0') >= 0) {
define('JSON_ENCODE_PARAM_SUPPORT', true);
}else{
define('JSON_ENCODE_PARAM_SUPPORT', false);
}
require_once("mpower/setup.php");
require_once("mpower/customdata.php");
require_once("mpower/checkout.php");
require_once("mpower/checkout/store.php");
require_once("mpower/checkout/checkout_invoice.php");
require_once("mpower/checkout/onsite_invoice.php");
require_once("mpower/direct_pay.php");
require_once("mpower/direct_card.php");
require_once("mpower/libraries/Requests.php");
require_once("mpower/utilities.php");
Now when i use require_once i get:
Class 'Libraries\MPowerLib\MPower_Checkout_Invoice' not found
However when i use just require it works but i keep getting this error:
Cannot redeclare class libraries\mpowerlib\mpower_checkout
I am totally perplexed by this, have played around with the code trying include and include_once but still no change.
1.Add the mpower composer package to your composer.json file instead of adding the library manually
"require": {
"laravel/framework": "5.2.*",
"sirakoff/mpower_php":"dev-master"
},
2.Autoload the package by adding this to your composer.json file
"psr-0": {
"Sirakoff\\":["src/"]
}
3. Set Mpower keys and Tokens in your controllers constructor method
public function __construct(){
\MPower_Setup::setMasterKey("dd6f2c90-f075-012f-5b69-00155d866600");
\MPower_Setup::setPublicKey("test_public_oDLVlm1eNyh0IsetdhdJvcl0ygA");
\MPower_Setup::setPrivateKey("test_private_zzF3ywvX9DE-OSDNhUqKoaTI4wc");
\MPower_Setup::setMode("test");
\MPower_Setup::setToken("ca03737cf942cf644f36");
}
4. Now you can make use of the package in your controller
public function makePayment(Request $request)
{
$co = new \MPower_Checkout_Invoice();
//addItem(name_of_item,quantity,unit_price,total_price,optional_description)
$co->addItem("13' Apple Retina 500 HDD",1,1.99,1.99);
$co->addItem("Case Logic laptop Bag",2,1.50,3.00,"Black Color with white stripes");
$co->addItem("Mordecai's Bag",2,1.99,3.98);
$co->setTotalAmount(8.97);
$co->setDescription("Payment for general goods.");
$co->addTax("VAT (15)",50);
$co->addTax("NHIL (10)",50)
$co->addCustomData("Firstname","Alfred");
$co->addCustomData("Lastname","Rowe");
$co->addCustomData("CartId",929292872);
if($co->create()) {
//Your code here
}
}

Categories