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
}
}
Related
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
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
I'm working with a old project. Classies have no namespacies.
Path structure:
-container // Container
--app
----model // all classies without namespace
----model_common // all classies used by other two projects without namespace
------Rede // new librarie with namespace
--------Exception
--------Service
----view
----controller
spl_autoload_register function is in a file named init_client.php, inside app path:
define('M_CMN', CLI_APP. 'model_common/'); // $_SERVER['DOCUMENT_ROOT'] . '/app/model_common/'
define('M_CLI', CLI_APP. 'model/'); // $_SERVER['DOCUMENT_ROOT'] . '/app/model/'
function autoload_client($class){
$path_and_class = str_replace('\\', DIRECTORY_SEPARATOR, $class); // May case there is a namespace
if (file_exists(M_CMN . "{$path_and_class}.php")): // First local to find class
require_once M_CMN . "{$path_and_class}.php";
elseif (file_exists(M_CLI . "{$path_and_class}.php")):
require_once M_CLI . "{$path_and_class}.php";
else :
ErrorFunction("Class {$path_and_class} was not found.",ERROR_1);
endif;
}
spl_autoload_register('autoload_client');
Example:
$consult = new DealConsult; // app/model
$consult->checkTransaction('123') // It will use Rede\Store, Rede\Environment and Rede\eRede classies
Error: Class Rede/Store was not found. But file $_SERVER['DOCUMENT_ROOT'] . '/app/model/Rede/Store.php' exist.
DealConsult.php class:
use Rede\Store;
use Rede\Environment;
use Rede\eRede;
class DealConsult {
public function checkTransaction($cod) {
$this->store = new Rede\Store($_SESSION['trans']['id_filiacao'], $_SESSION['trans']['token'], Rede\Environment::sandbox());
$this->transaction = (new Rede\eRede($this->store))->getByReference($cod);
printf("Autorization status: %s\n", $this->transaction->getAuthorization()->getStatus());
}
What am I not getting understand? I'm learning namespacies recently as well as PSR-4 defaults.
Use Composer to automatically load all the classes. In your composer.json file, you need to have:
{
"autoload": {
"psr-4": {
"Rede\\": "container/app/model_common/"
// Add as many classes as you need here in this map...
}
}
}
After that, run:
compose dump-autoload --optimize
Finally, include vendor/autoload.php where necessary.
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();
I am trying to load a php namespace into my symfony project but keep getting the following error at runtime.
Attempted to load class "FM" from namespace "VehicleTracking\Src\Vendors\FM".
Did you forget a "use" statement for another namespace?
The controller that it is being called from
namespace BWT\FMBundle\Controller;
use VehicleTracking\Src\Vendors\FM\FM;
class FMController extends Controller
{
/**
* #Route("/fuel_data", name="fuelData")
* #return \Symfony\Component\HttpFoundation\Response
*/
public function fuelDataAction(Request $request)
{
//...
$tripProcesses = new FM(); //<-this is the line where I get the error
$_results = $tripProcesses->getTripWithTotals($form->get('fleetNo')->getData(), $form->get('startDate')->getData(), $form->get('endDate')->getData());
}
}
The FM.php file. which is in the directory vendor/bwt/vehicle_tracking/src/vendors
tracking.interface and tracking.class are in the same directory
<?php
namespace VehicleTracking\Src\Vendors\FM;
// : Includes
include_once (dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . 'tracking.interface');
include_once (dirname(realpath(__FILE__)) . DIRECTORY_SEPARATOR . 'tracking.class');
// : End
use VehicleTracking\Src\Vendors\Vendors as Vendors;
use VehicleTracking\Src\Vendors\TrackingInterface as TrackingInterface;
class FM extends Vendors\Vendors implements TrackingInterface\TrackingInterface
{
public function getTrackingData()
{...}
}
autoload_namespace.php
<?php
// autoload_namespaces.php #generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
//...
'' => array($vendorDir . '/bwt/vehicle_tracking/src/vendors'),
);
We eventually solved this by adding
"autoload" : {
"psr-4" : {
"Vendors\\" : "src/"
}
},
to the composer.json of the external package and changed the namespace of the classes to namespace Vendors; so that it would be the same as the directory.
I have to run composer update -o to optimise the autoloader otherwise I keep getting these errors.
As a rule you should avoid editing anything under vendor. Your changes will be lost. In this case you can edit your projects composer.json file
"autoload": {
"psr-4": {
"": "src/",
"VehicleTracking\\Src\\Vendors\\FM\\": "vendor/bwt/vehicle_tracking/src/vendors"
},
After making changes, run composer dump-autoload to update the autoload stuff.
The path I gave is based on your question, at least that was the intent. It assumes that FM.php is located directly under vendor/bwt/vehicle_tracking/src/vendors
I only tested a fake FM.php class. That fact that there are include statements in there and some other strange code might generate additional errors.