PHP - Extend classes using composer autoloader causes redeclare error - php

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!

Related

Composer: Autoloaded file helper.php is autoloaded but the functions inside it are not

I am trying to make my own mock MVC framework as a project. This is my first time using composer outside of using it for requiring dependencies for Laravel. The actual autoloading works well, but when I try to autoload the helpers.php something weird happens. The file is autoloaded(if I change the path of the file I get the file not found error) but the contents inside it are not. In another file I try to call any function from the helpers.php file and I get
Fatal error: Uncaught Error: Call to undefined function
This is the file structure of the example
composer.json
App
Utils
helpers.php
public
index.php
This is my composer.json file:
{
"name": "admin/projecttest",
"autoload": {
"psr-4": {
"Admin\\Projecttest\\": "src/",
"App\\": "App/"
},
"files": [
"App/Utils/helpers.php"
]
},
"minimum-stability": "dev"
}
The helpers.php
<?php
namespace App\Utils;
use Leonlav77\Frejmcore\helpers\DotEnv;
function config($config){
$config = explode(".", $config);
$file = $config[0];
$configFile = require "../config/$file.php";
return $configFile[$config[1]];
}
function env($key, $default = null){
(new DotEnv(__DIR__ . '../../.env'))->load();
return getenv($key) ? getenv($key) : $default;
}
function baseDir(){
return __DIR__ . "/../";
}
index.php (where I call the function from the helper)
<?php
require "../vendor/autoload.php";
var_dump(function_exists('baseDir'));
var_dump(baseDir());
from the function_exists I get false
As the user Foobar suggested the the problem was in the namespace of the helpers.php . Since it had a namespace the functions also had a namespace, so insted of baseDir() I needed to use App/Utils/baseDir().
The solution was to simply remove the namespace from helpers.php

Controller not found in slim 3

I am new to slim,so please bear with me.
I have project structure like
\slim
  \public
    index.php
    
  \src
    \controllers
\reports
       BillingReportController.php
\routes
router.php
\config
db.php
But whenever I call the controller via route it gives me below error
"PHP Fatal error: Class 'src\controllers\reports\BillingReportController' not found in /var/www/html/apimod/public/index.php on line 13"
As for the line mentioned in error the snippet is as follows.
index.php
$container = $app->getContainer();
$container['BillingReportController'] = function($container){
return new \src\controllers\reports\BillingReportController;
};
router.php
$app->group('/report', function() use ($app) {
$app->get('/billing', 'BillingReportController:billing');
});
BillingReportController.php
namespace src\controllers\BillingReportController;
class BillingReportController{
public function billing($request, $response){
//my code goes here
}
}
Can anyone please point out the error.
You must've to use autoloading in your composer. something like this.
"autoload": {
"psr-4": {
"src\\": "src"
}
}
then in your terminal enter this command
composer dump-autoload
it should fix your problem

PHP - Namespace isn't working properly

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

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