Problem:
I have the following file structure
-api (contains index.php)
--src
---vendor
----auth (contains auth.php)
----bin
----composer
----nesbot
----rbdwllr
----sympfony
here is my composer.json
{
"autoload": {
"psr-4": {
"AuthSpace\\": "/auth",
"Tests\\": "/rbdwllr/reallysimplejwt/tests",
"Symfony\\Polyfill\\Mbstring\\": "/symfony/polyfill-mbstring",
"Symfony\\Component\\Translation\\": "/symfony/translation",
"ReallySimpleJWT\\Helper\\": "/rbdwllr/reallysimplejwt/src/Helper",
"ReallySimpleJWT\\Exception\\": "/rbdwllr/reallysimplejwt/src/Exception",
"ReallySimpleJWT\\": "/rbdwllr/reallysimplejwt/src",
"": "/nesbot/carbon/src"
}
}
}
index.php
require __DIR__ . '/src/vendor/autoload.php';
$argument1 = $_GET['argument1'];
$tokenCode = $_GET['tokenCode'];
include 'config/database.php';
include 'objects/program1.php';
include 'auth.php';
use ReallySimpleJWT\Token;
use Carbon\Carbon;
$secret = "somesecret";
if (($_SERVER['REQUEST_METHOD']) == "GET") {
if ($_GET['url'] == "bankquery") {
if($tokenCode===NULL){
echo "no correct token provided";
print($results);
} else {
$results = Token::validate($tokenCode, $secret);
if ($results = 1){
$var = new AuthClass();
$var = AuthClass::checkTime($tokenCode);
} else {
echo "no correct token provided";
}
}
} else {
echo "some GET other query";
}
?>
auth.php
<?php namespace AuthSpace;
use ReallySimpleJWT\Token;
use Carbon\Carbon;
class AuthClass{
public static function checkTime($tokenCode){
// getting payload from token code by accessing the composer dependency method in a class Token
$received = Token::getPayload($tokenCode);
return $received;
}}
?>
I've generated the autoload using composer dump-autoload, checked the prs4 links - they all seem to show correct directory and namespace linking.
But nontheless, after running index.php file i keep getting the following error, but don't know why.
PHP Fatal error: Uncaught Error: Class 'AuthSpace\AuthClass' not
found
Related
I can't seem to figure out why i keep getting this error even though everything seems correct.
My Composer.json looks like this:
{
"autoload": {
"psr-4": {
"Datechecker\\": "lib/",
"App\\": "app/"
}
}
}
And my class looks like this:
<?
namespace Datechecker;
class App
{
public function runCommand(array $argv){
$name = "World";
if(isset($argv[1])){
$name = $argv[1];
}
echo "Hello $name!!!\n";
}
}
Then my executable file looks like this:
#!/usr/bin/php
<?
require_DIR_.'/vendor/autoload.php';
if (php_sapi_name() !== 'cli') {
exit;
}
use Datechecker\App;
$app = new App();
$app->runCommand($argv);
?>
I have tried to follow similar questions which i came across on here but none of the solutions seem to be working for me. Please help.
Update
Classes structure looks like this:
lib/
App.php
app/
vendor/
composer/
...
autoload.php
datechecker
composer.json
Im trying to load a composer script into my class or function. But keeps getting the error:
Parse error: syntax error, unexpected 'use' (T_USE) in
I have searched on Stack Overflow and Google and read something about namespaces? But how can I implement a composer script into a class or function?
function.php, loads the autoload.php script file:
require(TEMPLATEPATH.'/vendor/autoload.php');
Custom function script:
function addToMailchimp($email) {
use \DrewM\MailChimp\MailChimp;
$MailChimp_api_key = get_field('mailchimp_api_key', 'option');
$MailChimp_landings_page = get_field('mailchimp_landings_page', 'option');
$MailChimp_landings_page_failed = get_field('mailchimp_landings_page_failed', 'option');
$MailChimp = new MailChimp($MailChimp_api_key);
if ($email != '') {
$list_id = '06b233d443';
$result = $MailChimp->post("lists/$list_id/members", [
'email_address' => $email,
'status' => 'subscribed',
]);
if ($result['detail'] == '') {
header( 'Location: ' . $MailChimp_landings_page['url']);
exit;
} else {
header( 'Location: ' . $MailChimp_landings_page_failed['url']);
exit;
}
}
}
composer.json file:
{
"require": {
"drewm/mailchimp-api": "^2.5",
"mpdf/mpdf": "^8.0"
},
"autoload": {
"psr-4": {
"DrewM\\MailChimp\\":"src/"
}
}
}
Autoloading would normally be setup on the initial page, most frequently in a front-controller or other .php file that is called first, and then organises what else happens. The 'use' statement also goes outside of the function, or class, and then the aliased class (here, MailChimp, is available within the whole file).
This code appears to be in a wordpress or older-style CMS system - it is possible to use composer within a plugin, or similar. There are examples of that around.
I am using these require statements in my root folder of project directory (in index.php).
require("./models/college/collegeModel.php");
require("./routes/routes.php");
require("./controllers/college/collegeController.php");
require("./controllers/home/homeController.php");
require("./controllers/login/loginController.php");
require("./controllers/logout/logoutController.php");
require("./controllers/public/publicController.php");
require("./lib/util.php");
and now I am trying to use composer autoload to load on demand by using composer.json file to remove all above require with single one :
require("./vendor/autoload.php");
My composer.json file is as follows
{
"name": "vermajnv/web",
"authors": [
{
"name": "vermajnv",
"email": "nayanrahul.jnv#gmail.com"
}
],
"require": {},
"autoload": {
"classmap": ["models/college", "controllers/college",
"controllers/home", "controllers/login", "controllers/logout",
"controllers/public", "lib/", "routes/"]
}
}
It works fine if I remove "lib/" and "routes/"
please provide me proper solution for this problem I'll be thankful to all.
oho.. I got what I was doing wrong
actually the util.php and routes.php does not contains a class to initialize the autoload_classmap.php
my util.php was before like this :
<?php
public function baseUrl($url) {
$contaxtPath = "/" . explode("/", $_SERVER['REQUEST_URI'])[1];
return $contaxtPath . $url;
}
public function redirect($to) {
$url = baseUrl($to);
header("Location:" . $url, 302);
}
Now I just make it wrapped with a class with static methods and these methods can be access through HTMLutill::
<?php
class HTMLutil {
// static method inside a class are visible every where without creating instance of class (HTMLutil) we can access it by HTML::baseUrl();
public static function baseUrl($url) {
$contaxtPath = "/" . explode("/", $_SERVER['REQUEST_URI'])[1];
return $contaxtPath . $url;
}
public static function redirect($to) {
$url = self::baseUrl($to);
header("Location:" . $url, 302);
}
}
Now my app is working fine.
happy coding guys..
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 have a strange bug at the moment in my web service I am coding.
When I am loading an specific url I get a success and error at the same time?
This is what I have in my index.php:
<?php
require_once 'functions/lib.php';
require_once 'core/init.php';
// Ask for request URL that was submitted and define scriptPath. Explode content of REQUEST URL to evaluate validity.
$requestURL = (($_SERVER['REQUEST_URI'] != "") ? $_SERVER['REQUEST_URI'] : $_SERVER['REDIRECT_URL']);
$scriptPath = dirname($_SERVER['PHP_SELF']);
$requestURL = str_replace($scriptPath, "", $requestURL);
$requestParts = explode("/", $requestURL);
// Check for valid api version
$validAPIVersions = array("v1");
$apiVersion = $requestParts[1];
// If API Version not in valid API array return 404, else OK.
if (!in_array($apiVersion, $validAPIVersions)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
echo "<br>" . "API Version not valid";
exit();
}
// Check for valid API endpoint
$validEndPoints = array("tickets");
$endPoint = $requestParts[2];
if (!in_array($endPoint, $validEndPoints)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
echo "<br>" . "Endpoint not valid";
exit();
}
// get the endpoint class name
$endPoint = ucfirst(strtolower($endPoint));
$classFilePath = "$apiVersion/$endPoint.php";
if (!file_exists($classFilePath)) {
httpResponseCode(404);
echo $GLOBALS['http_response_code'];
exit();
}
// load endpoint class and make an instance
try {
require_once($classFilePath);
$instance = new $endPoint($requestParts);
} catch (Exception $e) {
httpResponseCode(500);
echo $GLOBALS['http_response_code'];
exit();
}
and this is the corresponding "Tickets.php"
<?php
echo "OK";
?>
In the last two rows of my index.php, I am loading the specific class (named in the URL). For testing purposes, I have an "echo "OK" in this file. And this is the result when I am loading the URL I need:
http://api.medifaktor.de/v1/tickets
OK
Fatal error: Class 'Tickets' not found in /usr/www/users/kontug/api.medifaktor.de/webservice/index.php on line 45
I get the OK I was expecting AND the error for the Class Tickets, that is not found. Line 45 is
$instance = new $endPoint($requestParts);
Can someone give me a helping hand?
Best
Sebastian
The problem is that you don't have a class "Tickets" defined. After you load the tickets.php file, you are attempting to instantiate a class. Loading a file is not the same thing as defining a class. Within tickets.php (or some other included file), you need to define the class, like so:
class Tickets
{
// some properties here
private $endpoint;
// some methods here
public function __construct($endpoint)
{
$this->endpoint = $endpoint;
}
}
If you're not sure how to construct classes in PHP, read the section in the manual on classes.
Update: I added some example code within the class for version PHP5+.
Try the following for your test, in the 'ticket.php' file add:
class Ticket {
public function __construct()
{
echo 'testing';
}
}
Then make sure you either namespace or require the file.