Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Slim 3 autoloader

Tags:

php

autoload

slim

I'm new to slim framework, and can't figure out how to use the autoloader to autoload my classes.

I created a app/models/myclass.php but of course when I try to use it I get a class not found. I'm not sure which is the right way to autoload classes, or the naming convensions I should use. Should I do it via the composer.json somehow? I'm searching the net for several hours without any solid answer on that.

UPDATE:

Managed to do it like that:

  • added model in : app/src/Model/Client.php
  • added namespace App\Model; in Client.php
  • added the following in depedencies.php:
$container['App\Model\Client'] = function ($c) {
    return new App\Model\Client();
};

and routes.php:

$app->get('/client/ping/{id}',  function ($request, $response, $args)  {
    $container = $this->getContainer();
    $client=$container['App\Model\Client']; //instantiates a new Client
    ...
    ...
}
like image 211
sivann Avatar asked Jul 19 '15 11:07

sivann


People also ask

What is Composer's autoloader?

Composer is PHP's dependency manager tool. Composer allows you to specify libraries that are need for a project, and will automatically include those libraries along with their dependencies. Composer also allows you to create your own packages and share them via the Packagist website.

What is slim framework in PHP?

Slim is a PHP micro framework that helps you quickly write simple yet powerful web applications and APIs. php use Psr\Http\Message\ResponseInterface as Response; use Psr\Http\Message\ServerRequestInterface as Request; use Slim\Factory\AppFactory; require __DIR__ . '/../


2 Answers

For autoloading of own classes you should use Composer by adding some options to your composer.json:

{
    "require": {
        "slim/slim": "^3.9"
    },
    "autoload": {
        "psr-4": {
            "My\\Namespace\\": "src/"
        }
    }
}
// index.php
require 'vendor/autoload.php';

$app = new \Slim\App();
$myClass = new \My\Namespace\MyClass();

After running composer update composer will register your own namespaces and will autoload them for you.

like image 177
danopz Avatar answered Sep 20 '22 13:09

danopz


Add this in composer.json file Where app1 is the name of the folder you want to Autoload.

"autoload": {
    "psr-4":{
        "app1\\": "anything"
    }
}

After doing this run this in cmd (via composer)

composer dump-autoload -o
like image 45
Aklesh Singh Avatar answered Sep 19 '22 13:09

Aklesh Singh