PHP autoload can't find the class in php project - php

Project file structure
I'm getting
127.0.0.1:52368 [500]: GET /controllers/login - Uncaught Error: Class "App\Core\Database" not found in /path/to/my/Php/project/src/controllers/index.php:9
Stack trace:
#0 {main}
thrown in /path/to/my/Php/project/src/controllers/index.php on line 9
and the class firing an error
<?php
namespace App\controllers;
use App\Core\Database;
//$conn = Database::getConnection();
try {
$conn = new Database(__DIR__ . './../config.php');
} catch (\Exception $e) {
}
$query = "SELECT id, username, image, aboutme
FROM users
LEFT JOIN persons on users.id = persons.user_id
LIMIT 24";
$tbh = $conn->prepare($query);
$tbh->execute();
$persons = $tbh->fetchAll();
require_once basename("/") . 'views/index.view.php';
also my autoload_classmap.php
return array(
'App\\Core\\Database' => $baseDir . '/src/Core/Database.php',
'App\\Core\\DotEnv' => $baseDir . '/src/Core/DotEnv.php',
'App\\Core\\Router' => $baseDir . '/src/Core/Router.php',
'App\\Entity\\Person' => $baseDir . '/src/Entity/Person.php',
'App\\Entity\\User' => $baseDir . '/src/Entity/User.php',
And I'm launching server from src directory :
php -S localhost:8000
Any help would be appreciated. Thank you.
Edit ...
I'm calling index.php from url : localhost:8000 and even with this code in index.php
<?php
namespace App;
//use App\core\Database;
use App\Core\Router;
require 'functions.php';
//$config = require_once ('config.php');
//$db = new Database($config);
//require 'Entity/User.php';
$uri = parse_url($_SERVER['REQUEST_URI'])['path'];
$router = new Router();
$router->getRoute($uri);
//require 'router.php';
I'm getting
127.0.0.1:53738 [500]: GET / - Uncaught Error: Class "App\Core\Router" not found in

You must create a class and add data inside it .
prepare($query);
$tbh->execute();
$persons = $tbh->fetchAll();
require_once basename("/") . 'views/index.view.php';
}

Related

PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct() on PDO class

I am currently looking at improving my PHP knowledge and creating websites to a better extent by using classes and such but I've ran into an issue when trying to allow other classes in separate files to access the PDO connection that I've sent up. I've tried hundreds of resolutions which have been inputted onto this site but can't seem to figure it out at all and can't seem to understand where I'm going wrong.
I'm being met with the following error:
[16-Sep-2022 11:05:02 UTC] PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct(), 0 passed in /home/liamapri/public_html/kit/global.php on line 24 and exactly 1 expected in /home/liamapri/public_html/kit/app/class.core.php:11
Stack trace:
#0 /home/liamapri/public_html/kit/global.php(24): Kit\core->__construct()
#1 /home/liamapri/public_html/index.php(3): include_once('/home/liamapri/...')
#2 {main}
thrown in /home/liamapri/public_html/kit/app/class.core.php on line 11
I have a global.php file which will be added to each individually page such as /home /index etc, it references all the files that I'll need and starts the session from it, see below:
error_reporting(E_ALL ^ E_NOTICE);
define('C', $_SERVER["DOCUMENT_ROOT"].'/kit/conf/');
define('A', $_SERVER["DOCUMENT_ROOT"].'/kit/app/');
define('I', 'interfaces/');
// Management
require_once C . 'config.php';
// Interfaces
require_once A . I . 'interface.engine.php';
require_once A . I . 'interface.core.php';
require_once A . I . 'interface.template.php';
// Classes
require_once A . 'class.engine.php';
require_once A . 'class.core.php';
require_once A . 'class.template.php';
// OBJ
$engine = new Kit\engine();
$core = new Kit\core();
$template = new Kit\template();
// Start
session_start();
$template->Initiate();
This references the class.engine.php first which is where I have created the database connection class, as shown below:
namespace Kit;
use PDO;
if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }
class engine
{
public $pdo;
public function __construct()
{
global $_CONFIG;
$dsn = "mysql:host=".$_CONFIG['mysql']['hostname'].";dbname=".$_CONFIG['mysql']['database'].";charset=".$_CONFIG['mysql']['charset'].";port=".$_CONFIG['mysql']['port'].";";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
try {
$this->pdo = new PDO($dsn, $_CONFIG['mysql']['username'], $_CONFIG['mysql']['password'], $options);
} catch (\PDOException $e) {
print "<b>An error has occurred whilst connecting to the database:</b><br />" . $e->getMessage() . "";
die();
}
}
}
$connection = new engine();
I'm then trying to run a PDO query on another class (class.core.php) and keep getting met with either a PDO can't be found error or the one described above.
See the file below:
namespace Kit;
if(!defined('IN_INDEX')) { die('Sorry, this file cannot be viewed.'); }
class core implements iCore
{
public $connection;
public function __construct($connection)
{
$this->connection = $connection;
}
public function website_settings()
{
$qry = $this->connection->pdo->prepare("SELECT `website_name` FROM `kit_system_settings`");
$qry->execute([]);
if ($qry->rowCount() == 1) { while($row = $qry->fetch()) { return $row; } }
}
}
Sorry if this is a simple fix but I really can't see where I'm going wrong.
Look in your global .php on Line 24 (its probably this line: $core = new Kit\core();)
In your class.core.php you tell the constructor that it will get a connection, but in your global.php you dont give constructor (when you initialize a class) any argument.
That's what this error is telling you
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Kit\core::__construct(), 0 passed
Just guessing, but i think
$core = new Kit\core($engine->pdo);
will fix your issue.

PSR-2 namespace issue

I added a namespace to my user.php file, this causes an error to be displayed :
Fatal error: Uncaught Error: Class 'User' not found in /var/www/html/login.php:9 Stack trace: #0 {main} thrown in
/var/www/html/login.php on line 9
I tried changing "new Database\Database();" to "new \PDO();" but that causes another error which I've been unable to resolve after spending hours on google, if anyone could help I'd much appreciate it, thank you.
user.php
<?php
namespace User;
// 'user' object
class User
{
login.php
<?php
include_once "config/core.php";
$page_title = "Login";
$require_login = false;
include_once "login_checker.php";
include_once "config/database.php";
include_once "objects/user.php";
include_once "libs/php/pw-hashing/passwordLib.php";
$database = new Database\Database();
$db = $database->getConnection();
$user = new User($db);
use User\User;
$user = new User($db);

run script in background(shell_exec) fails on composer/PHP-DI function

I run that script manually and everything works,
$container = require '../config/bootstrap.php';
try {
$test = $container->get(Test::class);
$test->run();
}
catch(\Exception $e) {
echo $e->getMessage() . "\n";
die;
}
but when I call that file from another folder like the following :
$script = __DIR__ .'/folder/test-service.php';
$output = shell_exec('php '.$script);
var_dump($output);
I get the following error:
Fatal error: require(): Failed opening required '../config/bootstrap.php' (include_path='.:') in /anotherFolder/folder/test-service.php on line 13
and also after that, I got a lot of error that files do not exist.
bootstrap.php include the class mapping of PHP-DI
require '../vendor/autoload.php';
use DI\ContainerBuilder;
$containerBuilder = new ContainerBuilder;
$containerBuilder->addDefinitions(__DIR__ . '/config.php');
$container = $containerBuilder->build();
return $container;
The require instruction is relative to your current directory.
You could replace the line with require __DIR__.'/../config/bootstrap.php';

PDO query in Slim causes PHP Fatal error: Uncaught RuntimeException: Unexpected data in output buffer

So my basic slim app goes along these lines:
<?php
session_start();
if (!file_exists( __DIR__ . '/settings.php')) { die("Error 500: application configuration problem."); }
require __DIR__ . '/../vendor/autoload.php';
$config = require __DIR__ . '/settings.php';
$app = new \Slim\App($config);
$container = $app->getContainer();
$container['s4s'] = function ($container) {
$db = $container['settings']['s4s'];
return new PDO('sqlsrv:Server='.$db['host'].';Database='.$db['database'], $db['username'], $db['password']);
};
$app->get('/ff', function ($request, $response) {
$sql = 'SELECT "dbo"."ZAKAZKA"."ZAKAZKA ID" FROM "dbo"."ZAKAZKA" WHERE ("ZAKAZKA ID" LIKE \'1216%\' ) ORDER BY "dbo"."ZAKAZKA"."ZAKAZKA ID" DESC';
$stmt = $this->s4s->prepare($sql);
if($stmt->execute()){
echo $stmt->debugDumpParams();
$results=$stmt->fetchAll();
}
});
this works fine and dandy. If I move the query code to a controller
<?php
namespace Glued\Playground;
use \PDO;
use Glued\Controllers\Controller;
class pdo_test extends Controller
{
public function test($request, $response)
{
$sql = 'SELECT "dbo"."ZAKAZKA"."ZAKAZKA ID" FROM "dbo"."ZAKAZKA" WHERE ("ZAKAZKA ID" LIKE \'1216%\' ) ORDER BY "dbo"."ZAKAZKA"."ZAKAZKA ID" DESC';
echo $sql;
$stmt = $this->container->s4s->prepare($sql); // this line breaks things
if($stmt->execute()){
echo $stmt->debugDumpParams();
$results=$stmt->fetchAll();
}
}
}
and add to the main code
$app->get('/playground/fff', '\Glued\Playground\Pdo_test::mytest');
it starts to break at the $stmt assignment with the error
PHP Fatal error: Uncaught RuntimeException: Unexpected data in output buffer. Maybe you have characters before an opening finalize(Object(Slim\Http\Response))\n#1 /opt/Web/html/glued/vendor/slim/slim/Slim/App.php(298): Slim\App->process(Object(Slim\Http\Request), Object(Slim\Http\Response))\n#2 /opt/Web/html/glued/public/index.php(4): Slim\App->run()\n#3 {main}\n thrown in /opt/Web/html/glued/vendor/slim/slim/Slim/App.php on line 552
since this doesnt apply to other controllers I wrote sofar, I'm either overlooking something obvious or PDO (which I dont usually use) causes the premature output. Not sure how to debug this as well.
Hints and solutions very welcome, thanks in advance!
note: I usually dont work with mssql as well, but I got the same problem against a mysql db.

Fatal error: Class 'adLDAP' not found

The file I'm viewing is called examples.php and contains the following code:
include (dirname(__FILE__) . "/adLDAP.php");
try {
$adldap = new adLDAP();
}
The error that displays reads:
Fatal error: Class 'adLDAP' not found in /var/www/examples.php on line 14
Line 14 is:
$adldap = new adLDAP();
adLDAP.php is in the same folder as examples.php and contains the adLDAP class.
Have I messed up my include statement? I get "no such file or directory" with the other formats I have tried. Feels like I'm missing something obvious.
adLDAP.php instantiates the adLDAP class early on:
<?php
namespace adLDAP;
require_once(dirname(__FILE__) . '/collections/adLDAPCollection.php');
require_once(dirname(__FILE__) . '/classes/adLDAPGroups.php');
require_once(dirname(__FILE__) . '/classes/adLDAPUsers.php');
require_once(dirname(__FILE__) . '/classes/adLDAPFolders.php');
require_once(dirname(__FILE__) . '/classes/adLDAPUtils.php');
require_once(dirname(__FILE__) . '/classes/adLDAPContacts.php');
require_once(dirname(__FILE__) . '/classes/adLDAPExchange.php');
require_once(dirname(__FILE__) . '/classes/adLDAPComputers.php');
class adLDAP {
etc.
adLDAP class definition is in adLDAP namespace. You need to tell PHP that this class is in this namespace:
$adldap = new adLDAP\adLDAP();
You can also import this class with use keyword:
<?php
include (dirname(__FILE__) . "/adLDAP.php");
use adLDAP\adLDAP;
$adldap = new adLDAP;

Categories