PHP Autoloader not loading classes properly? - php

I have problem with autoloader not loading classes properly. I am not sure if I am doing it right... I am using slim framework.
My composer.json looks like this:
{
"require": {
"slim/slim": "^3.0",
"robmorgan/phinx": "^0.6.6",
"vlucas/phpdotenv": "^2.4",
"philo/laravel-blade": "3.*"
},
"autoload": {
"psr-4": {
"Cipo\\": ["app/"]
}
}
}
And my directory structure:
app/
Controllers/
Console/
AuthController.php
UsersController.php
HomeController.php
Core/
AbstractController.php
router.php
database/
public/
index.php
vendor/
views/
storage/
composer.json
My router.php looks like this:
$app->get("/", Cipo\Controllers\HomeController::class . ":index");
$app->get("/auth/login", Cipo\Controllers\Console\AuthController::class . ":getLogin");
The problem is that / works and shows the proper HTML, but /auth/login does not work. Here is the error that is thrown:
[Tue Jan 31 14:11:37.758803 2017] [:error] [pid 1336] [client 44.44.44.1:54453] Slim Application Error:
Type: RuntimeException
Message: Callable Cipo\\Controllers\\Console\\AuthController does not exist
File: /var/www/cipo.me/vendor/slim/slim/Slim/CallableResolver.php
Line: 62
Trace: #0 /var/www/cipo.me/vendor/slim/slim/Slim/CallableResolverAwareTrait.php(45): Slim\\CallableResolver->resolve('Cipo\\\\Controller...')
#1 /var/www/cipo.me/vendor/slim/slim/Slim/Route.php(333): Slim\\Routable->resolveCallable('Cipo\\\\Controller...')
#2 /var/www/cipo.me/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(116): Slim\\Route->__invoke(Object(Slim\\Http\\Request), Object(Slim\\Http\\Response))
#3 /var/www/cipo.me/vendor/slim/slim/Slim/Route.php(316): Slim\\Route->callMiddlewareStack(Object(Slim\\Http\\Request), Object(Slim\\Http\\Response))
#4 /var/www/cipo.me/vendor/slim/slim/Slim/App.php(438): Slim\\Route->run(Object(Slim\\Http\\Request), Object(Slim\\Http\\Response))
#5 /var/www/cipo.me/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(116): Slim\\App->__invoke(Object(Slim\\Http\\Request), Object(Slim\\Http\\Response))
#6 /var/www/cipo.me/vendor/slim/slim/Slim/App.php(332): Slim\\App->callMiddlewareStack(Object(Slim\\Http\\Request), Object(Slim\\Http\\Response))
#7 /var/www/cipo.me/vendor/slim/slim/Slim/App.php(293): Slim\\App->process(Object(Slim\\Http\\Request), Object(Slim\\Http\\Response))
#8 /var/www/cipo.me/public/index.php(45): Slim\\App->run()
#9 {main}
View in rendered output by enabling the "displayErrorDetails" setting.
And AuthController.php snippet:
<?php
namespace Cipo\Controllers\Console;
use PDO;
use Cipo\Core\AbstractController;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;
use Interop\Container\ContainerInterface;
/**
* Class AuthController
* #property \PDO db
* #property \Philo\Blade\Blade blade
*/
class AuthController extends AbstractController
{
// ...
public function getLogin(RequestInterface $request, ResponseInterface $response)
{
$response->getBody()->write($this->blade->view()->make("auth.login")->render());
return $response;
}
}

Related

Uncaught RuntimeException: Callable does not exist

I am trying a simple Slim application as shown below.
index.php
<?php
use Slim\Factory\AppFactory;
require './vendor/autoload.php';
$app = AppFactory::create();
$app->get('/', [TestController::class, 'showBlank']);
$app->run();
And below is the TestController.php.
<?php
use \Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;
use Slim\Http\Interfaces\ResponseInterface;
class TestController
{
protected $c;
public function __construct(ContainerInterface $c)
{
$this->c = $c;
}
public function showBlank(ServerRequestInterface $request, ResponseInterface $response, array $args): ResponseInterface
{
return $response;
}
}
Below is the project structure.
C:\laragon\www\chum>ls
composer.json composer.lock index.php TestController.php vendor
Since I am trying slim for first time, I am keep the example to very minimal and so the composer.json file.
{
"require": {
"slim/slim": "^4.11",
"slim/psr7": "^1.6",
"slim/twig-view": "^3.3",
"slim/http": "^1.3"
}
}
Given these, I am getting the below exceptio when I try to access the root page(\).
Fatal error: Uncaught RuntimeException: Callable TestController::showBlank() does not exist in C:\laragon\www\chum\vendor\slim\slim\Slim\CallableResolver.php:138
Stack trace:
#0 C:\laragon\www\chum\vendor\slim\slim\Slim\CallableResolver.php(90): Slim\CallableResolver->resolveSlimNotation('TestController:...')
#1 C:\laragon\www\chum\vendor\slim\slim\Slim\CallableResolver.php(63): Slim\CallableResolver->resolveByPredicate('TestController:...', Array, 'handle')
#2 C:\laragon\www\chum\vendor\slim\slim\Slim\Routing\Route.php(340): Slim\CallableResolver->resolveRoute(Array)
#3 C:\laragon\www\chum\vendor\slim\slim\Slim\MiddlewareDispatcher.php(65): Slim\Routing\Route->handle(Object(Slim\Http\ServerRequest))
#4 C:\laragon\www\chum\vendor\slim\slim\Slim\MiddlewareDispatcher.php(65): Slim\MiddlewareDispatcher->handle(Object(Slim\Http\ServerRequest))
#5 C:\laragon\www\chum\vendor\slim\slim\Slim\Routing\Route.php(315): Slim\MiddlewareDispatcher->handle(Object(Slim\Http\ServerRequest))
#6 C:\laragon\www\chum\vendor\slim\slim\Slim\Routing\RouteRunner.php(68): Slim\Routing\Route->run(Object(Slim\Http\ServerRequest))
#7 C:\laragon\www\chum\vendor\slim\slim\Slim\MiddlewareDispatcher.php(65): Slim\Routing\RouteRunner->handle(Object(Slim\Http\ServerRequest))
#8 C:\laragon\www\chum\vendor\slim\slim\Slim\App.php(199): Slim\MiddlewareDispatcher->handle(Object(Slim\Http\ServerRequest))
#9 C:\laragon\www\chum\vendor\slim\slim\Slim\App.php(183): Slim\App->handle(Object(Slim\Http\ServerRequest))
#10 C:\laragon\www\chum\index.php(56): Slim\App->run() #11 {main} thrown in C:\laragon\www\chum\vendor\slim\slim\Slim\CallableResolver.php on line 138
Thanks Alvaro for the great tips in comments, I was able to solve it with some further help from Google based on that.
I was under assumption flat project structure does not need namespaces to be configured. But I was wrong.
I did the below updates to composer.json file and ran composer dump-autoload -o.
"autoload": {
"psr-4": {
"App\\": ""
}
},

Why can "Class 'DI\Bridge\Slim\App'" not be found? PHP

I am trying to create a shopping cart for my website, I am following the tutorial below: https://www.youtube.com/watch?v=tRh467FX12U&list=PLfdtiltiRHWH9JN1NBpJRFUhN96KBfPmd&index=2
In the tutorial, he uses 3 different imports from GitHub and this is how installed them in the terminal using composer:
rosscurrie = Name of ~user
#Ross-Air = Name of Macbook
MobileMastersNew = Name of the folder that holds all website files
composer = is installed globally
require <...> = the imports from GitHub
rosscurrie#Rosss-Air MobileMastersNew % composer require slim/slim:^4.0
rosscurrie#Rosss-Air MobileMastersNew % composer require slim/twig-view:^3.0
rosscurrie#Rosss-Air MobileMastersNew % composer require php-di/slim-bridge
rosscurrie#Rosss-Air MobileMastersNew % composer require illuminate/database
I have limited experience with Laravel but not completely unfamiliar. When I try to load the index.php page it gets this error:
Fatal error: Uncaught Error: Class 'DI\Bridge\Slim\App' not found in /Users/rosscurrie/Sites/MobileMastersNew/app/App.php:8 Stack trace: #0 /Users/rosscurrie/Sites/MobileMastersNew/vendor/composer/ClassLoader.php(444): include() #1 /Users/rosscurrie/Sites/MobileMastersNew/vendor/composer/ClassLoader.php(322): Composer\Autoload\includeFile('/Users/rosscurr...') #2 [internal function]: Composer\Autoload\ClassLoader->loadClass('Cart\\App') #3 /Users/rosscurrie/Sites/MobileMastersNew/bootstrap/app.php(9): spl_autoload_call('Cart\\App') #4 /Users/rosscurrie/Sites/MobileMastersNew/public/index.php(3): require('/Users/rosscurr...') #5 {main} thrown in /Users/rosscurrie/Sites/MobileMastersNew/app/App.php on line 8
My folder directory is as follows:
My ../MobileMasters/app/App.php is:
<?php
namespace Cart;
use DI\ContainerBuilder;
use DI\Bridge\Slim\App as DIBridge;
class App extends DIBridge
{
protected function configureContainer(ContainerBuilder $builder)
{
$builder->addDefinitions([
'settings.displayErrorDetails' => true,
]);
//
}
}
My ../MobileMasters/bootstrap/app.php is:
<?php
session_start();
use Cart\App;
require __DIR__ . '/../vendor/autoload.php';
$app = new App;
My ../MobileMasters/public/.htaccess file is:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
My ../MobileMasters/public/index.php is:
<?php
require __DIR__ . '/../bootstrap/app.php';
$app->run();
My ../MobileMasters/vendor/autoload.php is:
<?php
// autoload.php #generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit2e9ebb4be0f95ed0dbfb26486b8ba4b7::getLoader();
Lastly, my ../MobileMasters/composer.json is:
{
"require": {
"slim/slim": "^4.0",
"slim/twig-view": "^3.0",
"php-di/slim-bridge": "^3.0",
"illuminate/database": "^7.2"
},
"autoload": {
"psr-4": {
"Cart\\": "app"
}
}
}
You should use use statement after autoloading:
<?php
namespace Cart;
use DI\ContainerBuilder;
use DI\Bridge\Slim\App as DIBridge;
class App extends DIBridge
{
protected function configureContainer(ContainerBuilder $builder)
{
$builder->addDefinitions([
'settings.displayErrorDetails' => true,
]);
//
}
}
And change this file also:
session_start();
require __DIR__ . '/../vendor/autoload.php';
use Cart\App;
$app = new App;
You are using wrong namespace use DI\Bridge\Slim\App as DIBridge;. There is no App class in DI package anymore.
Instead
use the following code use DI\Bridge\Slim\Bridge as DIBridge;
Your composer.json needs to look almost exactly like the one in the tutorial. I had the exact same problem. To require the older versions, you just have to do something like composer remove slim/slim then composer require slim/slim ^3.0.
In particular, the your php-di needs to be lower than v1.1. My composer.json:
{
{
"require": {
"slim/slim": "^3.0",
"slim/twig-view": "^2.1",
"illuminate/database": "^5.2",
"php-di/slim-bridge": "v1.0.2"
},
"autoload": {
"psr-4": {
"Cart\\": "app/"
}
}
}

Dependency injection cannot be handled using php-di

This is a problem that drove me crazy for over one week. I installed php-di via composer and added my own project to the composer.json file:
{
"name": "mypackage/platform",
"description": "MyPackage Platform",
"type": "project",
"require": {
"php-di/php-di": "^6.0"
},
"autoload": {
"psr-4": {
"MyPackage\\": "src/"
}
}
}
Then I created mine /public/index.php:
<?php
require_once dirname(__DIR__) . '/vendor/autoload.php';
use DI\ContainerBuilder;
use function DI\create;
use MyPackage\Base\Service;
$containerBuilder = new ContainerBuilder();
$containerBuilder->useAutowiring(false);
$containerBuilder->useAnnotations(false);
$containerBuilder->addDefinitions([
Service::class => create(Service::class)
]);
$container = $containerBuilder->build();
$service = $container->get('Service');
$service->showMessage();
And this is /src/Base/Service.php content:
<?php
namespace MyPackage\Base;
class Service
{
public function __construct()
{
}
public function showMessage()
{
echo "<BR>Inside Service";
}
}
When I troy to load index.php, Apache says:
[Thu Dec 05 18:57:47 2019] [error] PHP Fatal error: Uncaught DI\\NotFoundException: No entry or class found for 'Service' in /var/www/html/vendor/php-di/php-di/src/Container.php:135
Stack trace:
#0 /var/www/html/public/index.php(22): DI\\Container->get('Service')
#1 {main}
thrown in /var/www/html/vendor/php-di/php-di/src/Container.php on line 135
Whats is wrong with my approach?
$container->get('Service') asks the container for the entry 'Service'. This is a string. There is no namespace.
In your configuration, you configured the service under the Service::class key: Service::class returns the full class name, which is MyPackage\Base\Service.
So the error is: you have the service under MyPackage\Base\Service, and you try to fetch it via the key Service.

Slim framework Message: Callable Homecontroller does not exist

Project Structure
public/index.php
<?php
require __DIR__ . '/../vendor/autoload.php';
ini_set('display_errors', 'On');
if (PHP_SAPI == 'cli-server') {
// To help the built-in PHP dev server, check if the request was actually for
// something which should probably be served as a static file
$url = parse_url($_SERVER['REQUEST_URI']);
$file = __DIR__ . $url['path'];
if (is_file($file)) {
return false;
}
}
session_start();
// Instantiate the app
$settings = require __DIR__ . '/../src/settings.php';
$app = new \Slim\App($settings);
// Set up dependencies
require __DIR__ . '/../src/dependencies.php';
// Register middleware
require __DIR__ . '/../src/middleware.php';
// Register routes
require __DIR__ . '/../src/routes.php';
// Run app
$app->run();
Here we have the composer.json
{
"autoload":{
"psr-4": {
"App\\": "src"
}
},
"require": {
"php": ">=5.5.0",
"slim/slim": "^3.1",
"slim/php-view": "^2.0",
"monolog/monolog": "^1.17",
"illuminate/database": "~5.1",
"slim/twig-view": "^2.3"
},
"require-dev": {
"phpunit/phpunit": ">=4.8 < 6.0"
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"config": {
"process-timeout" : 0
},
}
Here is my controller, i obtain a error with the namespace and in all the examples that i have seen use this so.. I don't know what to do more
<?php
namespace \App\Controllers;
class Homecontroller
{
protected $container;
// constructor receives container instance
public function __construct(ContainerInterface $container) {
$this->container = $container;
}
public function home($request, $response, $args) {
echo "locura";
// your code
// to access items in the container... $this->container->get('');
return $response;
}
public function contact($request, $response, $args) {
// your code
// to access items in the container... $this->container->get('');
return $response;
}
}
Actual configuration
In my routes.php I have put this:
$app->get('/new', \Homecontroller::class . ':home');
Before configuration
In the above code, I tried to create the controller into the container, and then use
$app->get('/new', '\HomeController:home');
And in the dependencies.php I put this code:
$container['HomeController'] = function($c) {
$view = $c->get("view"); // retrieve the 'view' from the container
return new HomeController($view);
};
but I didn't obtain any result with any configuration
I would like to load the HomeController from router
This is the error that I have when I put api.powertv/new
Type: RuntimeException
Message: Callable Homecontroller does not exist
File: /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php
Line: 90
i come here, and I put this post like my last resource, if this fails I don't know what I am going to do.
Try to use absolute namespace path in your:
dependencies.php
$container['yourController'] = function ($c) {
$view = $c['view'];
return new \App\Controllers\YourController($view);
}
routes.php
$app->get('your_defined_route_name', \App\Controllers\YourController::class . ':YourControllerMethod');
The name inside the container and thoose who you use in the route must match
You've been set the container key to HomeController and used \HomeController in the route, these strings are not equal.
either self create the strings
$container['HomeController'] = function($c) {
$view = $c->get("view"); // retrieve the 'view' from the container
return new HomeController($view);
};
$app->get('/new', 'HomeController:home');
or use the ::class syntax for both:
$container[HomeController::class] = function($c) {
$view = $c->get("view"); // retrieve the 'view' from the container
return new HomeController($view);
};
$app->get('/new', [HomeController::class, 'home');
// or $app->get('/new', HomeController::class . ':home');
with the answer of Pheara I obtain another error, is the next:
Type: Error
Message: Undefined constant 'App\controllers'
File:/Users/alfonso/Sites/powertv_api/src/Controllers/HomeController.php
Line: 5
the trace of the error is the next:
/Users/alfonso/Sites/powertv_api/vendor/composer/ClassLoader.php(444): include()
#1 /Users/alfonso/Sites/powertv_api/vendor/composer/ClassLoader.php(322): Composer\Autoload\includeFile('/Users/alfonso/...')
#2 [internal function]: Composer\Autoload\ClassLoader- >loadClass('App\\Controllers...')
#3 [internal function]: spl_autoload_call('App\\Controllers...')
#4 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php(89): class_exists('App\\Controllers...')
#5 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolver.php(67): Slim\CallableResolver->resolveCallable('App\\Controllers...')
#6 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/CallableResolverAwareTrait.php(45): Slim\CallableResolver->resolve('App\\Controllers...')
#7 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/Route.php(330): Slim\Routable->resolveCallable('App\\Controllers...')
#8 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(117): Slim\Route->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#9 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/Route.php(313): Slim\Route->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#10 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/App.php(495): Slim\Route->run(Object(Slim\Http\Request), Object(Slim\Http\Response))
#11 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/MiddlewareAwareTrait.php(117): Slim\App->__invoke(Object(Slim\Http\Request), Object(Slim\Http\Response))
#12 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/App.php(388): Slim\App->callMiddlewareStack(Object(Slim\Http\Request), Object(Slim\Http\Response))
#13 /Users/alfonso/Sites/powertv_api/vendor/slim/slim/Slim/App.php(296): Slim\App->process(Object(Slim\Http\Request), Object(Slim\Http\Response))
#14 /Users/alfonso/Sites/powertv_api/public/index.php(39): Slim\App->run()
#15 {main}
For solve this error you have to put the namespace in the 3 line:
<?php
namespace [yournamespace]
//rest of your controller

Laravel - bindings file for repositories

So I have an App\bindings.php file that I have added to my composer.json file as so:
"autoload": {
"files": [
"app/bindings.php"
]
},
In this file I am trying to set up bindings for my repositories like so:
<?php
function getRepoBinding($id)
{
$repo = "{$id}Repository";
$clientName = strtoupper(config('client.name'));
$implementation = config('app.repo_implementation', 'Eloquent');
$clientOverride = "App\Overrides\\{$clientName}\Repositories\\{$implementation}\\{$repo}";
$repo = class_exists($clientOverride) ? $clientOverride : "App\Repositories\\{$implementation}\\{$repo}";
return $repo;
}
// Repository Interface Bindings
dd(getRepoBinding('Contribution'));
App::bind('ContributionIneterface', getRepoBinding('Contribution'));
However, i run a composer dump-auto and try to run my application and I get the following error:
Fatal error: Uncaught Error: Call to a member function make() on null in /home/vagrant/Code/famsapi/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:54
Stack trace: #0 /home/vagrant/Code/famsapi/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php(158): app('config')
#1 /home/vagrant/Code/famsapi/app/bindings.php(9): config('client.name')
#2 /home/vagrant/Code/famsapi/app/bindings.php(16): App\getRepoBinding('Contribution')
#3 /home/vagrant/Code/famsapi/vendor/composer/autoload_real.php(55): require('/home/vagrant/C...')
#4 /home/vagrant/Code/famsapi/vendor/composer/autoload_real.php(45): composerRequire03fe235c8b3156f0c5fcebbc0d696734('90f93262f3a0ac8...', '/home/vagrant/C...')
#5 /home/vagrant/Code/famsapi/vendor/autoload.php(7): ComposerAutoloaderInit03fe235c8b3156f0c5fcebbc0d696734::getLoader()
#6 /home/vagrant/Code/famsapi/bootstrap/autoload.php(17): require('/home/vagrant/C...')
#7 /home/vagrant/Code/famsapi/public/index.php(22): require('/home/vagrant/C...')
#8 {main} thrown in /home/vagrant/Code/famsapi/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php on line 54
It seems like it is having with the global config helper method...but im not sure how to fix that. Better yet, if you have an idea of how I can do this another way I am all ears.
It is because you are loading that file before the application starts.
Use it inside your AppServiceProvider

Categories