skip to Main Content

Good Morning,

Firstly, I want to inform you that English is not my first language, and I apologize for my imperfect English. I’m also new to use networks
.
I installed Slim and I test it with a crud with success

I want now to install with slim the Doctrine ORM, like this:
slimframework

In the bootstrap.php, there are underlines ("Undefined type").

bootstrap.php

here the accessible code:

<?php

namespace Appconfig;
// bootstrap.php

use DoctrineCommonCachePsr6DoctrineProvider;
use DoctrineORMEntityManager;
use DoctrineORMToolsSetup;
use SymfonyComponentCacheAdapterArrayAdapter;
use SymfonyComponentCacheAdapterFilesystemAdapter;
use UMADICContainer;

$container = new Container(require __DIR__ . '/settings.php');

$container->set(EntityManager::class, static function (Container $c): EntityManager {
    /** @var array $settings */
    $settings = $c->get('settings');

    // Use the ArrayAdapter or the FilesystemAdapter depending on the value of the 'dev_mode' setting
    // You can substitute the FilesystemAdapter for any other cache you prefer from the symfony/cache library
    $cache = $settings['doctrine']['dev_mode'] ?
        DoctrineProvider::wrap(new ArrayAdapter()) :
        DoctrineProvider::wrap(new FilesystemAdapter(directory: $settings['doctrine']['cache_dir']));

    $config = Setup::createAttributeMetadataConfiguration(
        $settings['doctrine']['metadata_dirs'],
        $settings['doctrine']['dev_mode'],
        null,
        $cache
    );

    return EntityManager::create($settings['doctrine']['connection'], $config);
});

return $container;


($routes = require __DIR__ . '/routes.php')($app);
  • The classes importations seem good (no underline). But most of the folders and classes of the code doesn’t exist in the folder "vendor")

  • I have tried to delete the folder vendor and the composer.lock folder:

rm -rf vendor/ composer.lock

then

require composer
  • I have reinstalled with no success.

  • The problem is the same with phpStorm.

Thank’s for your help.

2

Answers


  1. Chosen as BEST ANSWER

    I think after reading and progamming,, I think I understand some things. I'm a beginner in framework, so, please be indulgent. I hope I don't say stupid things.

    Last program:

    • It doesn't have a good structure because I followed an old version of Doctrine.
    • If I understand,the last program needs the doctrine console because the container uma/dic wich can't do autowiring/ The PHP-DI make it.

    The new program (Slim - PHP-DI - Doctine) - it's 's work. I have used:

    Secutiy and gestion management and error management are not implemented at the moment Here are the programs:

    • public/index: (tutorial code)
    <?php
    (require __DIR__ . '/../config/bootstrap.php')->run();
    
    • config/bootstrap (code of the tutorial)
    use DIContainerBuilder;
    use SlimApp;
     
    require_once __DIR__ . '/../vendor/autoload.php';
     
    // Construire l'instance de container de type PHP-DI
    $container = (new ContainerBuilder())
        ->addDefinitions(__DIR__ . '/container.php')
        ->build();
    
     
    //  renvoyer l'instance du container
    return $container->get(App::class);
    
    • config/settings.php (personnal code)
    <?php
    // settings.php
    return [
        'doctrine' => [
            'pathToModels' => '__DIR__ . /../src/Models',
            'isDevMode' => true,
            'connectionMysql' => [
                'driver' => 'pdo_mysql',
                'dbname' => 'university',
                'user' => 'toto',
                'password' => 'mdp',
            ],
        ],
    ];
    
    • config/container.php (tutorial code modified)
    <?php
     
    use SlimApp;
    use SlimFactoryAppFactory;
    use DoctrineDBALDriverManager; 
    use DoctrineORMEntityManager; 
    use DoctrineORMORMSetup;
    use PsrContainerContainerInterface; 
     
    return[
        'settings' => function () {
            $settings = require __DIR__ . '/settings.php';
            return $settings;
        },
        // Construction de l'instance EntutyManager
        EntityManager::class => function (ContainerInterface $container) : EntityManager {
     
            $settings = (array)$container->get('settings')['doctrine'];
     
     
            $paths = [$settings['pathToModels']]; //chemin de l'entité
            $isDevMode = $settings['isDevMode']; // est-ce en développement?
     
            // paramètres de connexion
            $dbParams = $settings['connectionMysql']; //connexion de la base de données
     
            // construction er retour de l'instance AppFactory
            $config = ORMSetup::createAttributeMetadataConfiguration($paths, $isDevMode);
            $connection = DriverManager::getConnection($dbParams, $config);
            return new EntityManager($connection, $config);   
        },
     
        // construction de l'application $app
        App::class => function (ContainerInterface $container) {
            $app = AppFactory::createFromContainer($container);
     
            // Register routes
            (require __DIR__ . '/routes.php')($app);
     
            // Register middleware
            (require __DIR__ . '/middleware.php')($app);
     
            return $app;
        }
    ];
    
    • config/routes.php (code personnal code)
    <?php
     
    use SlimApp;
    use AppControllersStudentController;
    use PsrHttpMessageServerRequestInterface as Request;
    use PsrHttpMessageResponseInterface as Response;
     
    return function (App $app) {
        //route de test
        $app->get('/', function (Request $request, Response $response) {
            $response->getBody()->write('Hello, World!');
            return $response;
        });
        //Appel de la méthode createUser de la classe StudentContreller à l'aide de l'URL "localhost:8082/create/student"
        $app->post('/create/student', StudentController::class . ':createStudent');
    };
    
    • src/Contollers/StudentController.php (code perso)
    <?php
     
    namespace AppControllers;
     
    use AppModelsStudent;
    use DoctrineORMEntityManager;
    use PsrHttpMessageResponseInterface as Response;
    use PsrHttpMessageServerRequestInterface as Request;
     
    class StudentController
    {
        private  $entityManager;
     
        public function __construct(EntityManager $entityManager){
            $this->entityManager = $entityManager;
        }
     
        public function createStudent(Request $request, Response $response): Response
        {
            //récupération des données
            $data = $request->getParsedBody();
            error_log(print_r($data, true), 3, __DIR__ . '/StudentController.log');
     
            // création des données de l'étudiant
            $student = new Student();
            $student->setName($data['name']);
            $student->setFirstname($data['firstname']);
            $student->setAge($data['age']);
     
            //transfert des données de l'étudiant dans la base de données
            $this->entityManager->persist($student);
            $this->entityManager->flush();
     
            $response->getBody()->write('Étudiant créé avec succès avec l'ID :' . $student->getId());
            return $response->withHeader('Content-Type', 'application/json');
        } 
    }
    

    src/Models/student.php (personnal code):

    <?php
    
    namespace AppModels;
    
    //Student.php
    
    use DoctrineORMMapping as ORM;
    
    #[ORMEntity]
    #[ORMTable(name: "students")]
    class Student{
    
        #[ORMId]
        #[ORMColumn(type: "integer")]
        #[ORMGeneratedValue]
        private $id;
    
        #[ORMColumn(type: "string", length: 50, nullable: false)]
        private $name;
    
        #[ORMColumn(type: "string", length: 50, nullable: false)]
        private $firstname;
    
        #[ORMColumn(type: "integer", nullable: false)]
        private $age;
    
        // Getter de l'Id
        public function getId()
        {
            return $this->id;
        }
    
        // Getter et setterde "name" 
        public function getName()
        {
            return $this->name;
        }
    
        public function setName($name): void
        {
            $this->name = $name;
        }
    
        // Getter et setter pour firstname
        public function getFirstname()
        {
            return $this->firstname;
        }
    
        public function setFirstname($firstname): void
        {
            $this->firstname = $firstname;
        }
    
        // Getter et setter pour "age"
        public function getAge()
        {
            return $this->age;
        }
    
        public function setAge($age): void
        {
            $this->age = $age;
        } 
    }
    
    I can hear your remarks.
    I especially want to thank Daniel Opitz for his fabulous work.
    

  2. Since there are lot of classes that are not available (and the slim documentation is not updated according to the last version of packages), you will have to adapt the code yourself. For example, DoctrineProvider class was abandoned after "doctrine/orm": "^2.19". So you will have to change your bootstrap file like this:

    <?php
    
    // bootstrap.php
    
    use DoctrineDBALDriverManager;
    use DoctrineORMEntityManager;
    use DoctrineORMORMSetup;
    use SymfonyComponentCacheAdapterArrayAdapter;
    use SymfonyComponentCacheAdapterFilesystemAdapter;
    use UMADICContainer;
    
    require_once __DIR__ . '/vendor/autoload.php';
    
    $container = new Container(require __DIR__ . '/settings.php');
    
    $container->set(EntityManager::class, static function (Container $c): EntityManager {
        /** @var array $settings */
        $settings = $c->get('settings');
    
        // Use the ArrayAdapter or the FilesystemAdapter depending on the value of the 'dev_mode' setting
        // You can substitute the FilesystemAdapter for any other cache you prefer from the symfony/cache library
        $cache = $settings['doctrine']['dev_mode'] ?
            new ArrayAdapter() :
            new FilesystemAdapter(directory: $settings['doctrine']['cache_dir']);
    
        $config = ORMSetup::createAttributeMetadataConfiguration(
            $settings['doctrine']['metadata_dirs'],
            $settings['doctrine']['dev_mode'],
            null,
            $cache
        );
    
        $connection = DriverManager::getConnection($settings['doctrine']['connection']);
        return new EntityManager($connection, $config);
    });
    
    return $container;
    

    Enough talking, i created a basic example
    php slim basic from Github Codespaces with php 8.2

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search