Ok.
The class StudentController has been generated by ChatGPT
this is my composer.json:
{
"name": "gerard/slim-crud3",
"autoload": {
"psr-4": {
"App\\": "src/"
}
},
"authors": [
{
"name": "Gérard Le Rest",
"email": "gerard.lerest@orange.fr"
}
],
"require": {
"slim/slim": "^4.13",
"slim/psr7": "^1.6",
"php-di/php-di": "^7.0",
"symfony/cache": "^6.4",
"doctrine/dbal": "^4.0",
"doctrine/orm": "^3.1",
"doctrine/doctrine-bundle": "^2.12",
"doctrine/cache": "^2.2",
"doctrine/migrations": "^3.7",
"uma/dic": "^3.0"
}
}
the index.php:
<?php
// index.php
use Slim\Factory\AppFactory;
// Charger le fichier de configuration
require __DIR__ . '/../vendor/autoload.php';
// Charger le fichier de configuration
require __DIR__ . '/../config/bootstrap.php';
// Créer l'application Slim
$app = AppFactory::create();
//charger la route
(require __DIR__ . '/../config/routes.php')($app);
$app->run(); // Démarre l'application
and bootstrap.php:
<?php
// bootstrap.php
use Doctrine\ORM\ORMSetup;
use Symfony\Component\Cache\Adapter\ArrayAdapter;
use Symfony\Component\Cache\Adapter\FilesystemAdapter;
use UMA\DIC\Container;
use Doctrine\ORM\EntityManager;
use App\Service\UserService;
$container = new Container(require __DIR__ . '/settings.php');
$container->set(EntityManager::class, static function (Container $c): EntityManager {
/** @var array $settings */
$settings = $c->get('settings');
$config = ORMSetup::createAttributeMetadataConfiguration(
$settings['doctrine']['metadata_dirs'],
$settings['doctrine']['dev_mode'],
null,
$settings['doctrine']['dev_mode'] ?
new ArrayAdapter() :
new FilesystemAdapter(directory: $settings['doctrine']['cache_dir'])
);
return new EntityManager($settings['doctrine']['connection'], $config);
});
// définir un service dans un conteneur d'injection de dépendances.
$container->set(UserService::class, static function (Container $c) {
return new UserService($c->get(EntityManager::class));
});
``
return $container;
the settings.php:
<?php
// settings.php
define('APP_ROOT', __DIR__);
return [
'settings' => [
'slim' => [
// Returns a detailed HTML page with error details and
// a stack trace. Should be disabled in production.
'displayErrorDetails' => true,
// Whether to display errors on the internal PHP log or not.
'logErrors' => true,
// If true, display full errors with message and stack trace on the PHP log.
// If false, display only "Slim Application Error" on the PHP log.
// Doesn't do anything when 'logErrors' is false.
'logErrorDetails' => true,
],
'doctrine' => [
// Enables or disables Doctrine metadata caching
// for either performance or convenience during development.
'dev_mode' => true,
// Path where Doctrine will cache the processed metadata
// when 'dev_mode' is false.
'cache_dir' => APP_ROOT . '/var/doctrine',
// List of paths where Doctrine will search for metadata.
// Metadata can be either YML/XML files or PHP classes annotated
// with comments or PHP8 attributes.
'metadata_dirs' => [APP_ROOT . '/src/Domain'],
// The parameters Doctrine needs to connect to your database.
// These parameters depend on the driver (for instance the 'pdo_sqlite' driver
// needs a 'path' parameter and doesn't use most of the ones shown in this example).
// Refer to the Doctrine documentation to see the full list
// of valid parameters: https://www.doctrine-project.org/projects/doctrine-dbal/en/current/reference/configuration.html
'connection' => [
'driver' => 'pdo_mysql',
'host' => 'localhost',
'port' => 3306,
'dbname' => 'mydb',
'user' => 'user',
'password' => 'secret',
'charset' => 'utf-8'
]
]
]
];
the routes.php:
```php
<?php
//routes.php
use App\Controllers\StudentController;
use Slim\App;
return function (App $app) {
// Définition des routes
$app->post('/create/student', StudentController::class . ':createStudent');
};
the StudentController.php:
<?php
namespace App\Controllers;
//StudentController.php
use App\Entities\Student;
use Doctrine\ORM\EntityManager;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class StudentController
{
private EntityManager $entityManager;
public function __construct(EntityManager $entityManager)
{
$this->entityManager = $entityManager;
}
public function createStudent(Request $request, Response $response, array $args): Response
{
$data = $request->getParsedBody();
$student = new Student();
if (isset($data['name'])) {
$student->setName($data['name']);
}
if (isset($data['firstname'])) {
$student->setFirstname($data['firstname']);
}
if (isset($data['age'])) {
$student->setAge($data['age']);
}
$response->getBody()->write("étudiant rentré avec succès");
try {
// Utilisez $this->entityManager pour interagir avec 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());
} catch (\Exception $e) {
$response->getBody()->write('Erreur lors de la création de l\'étudiant : ' . $e->getMessage());
return $response->withStatus(500);
}
return $response->withHeader('Content-Type', 'application/json');
}
}
Student.php:
<?php
namespace App\Entities;
//Student.php
use Doctrine\ORM\Mapping as ORM;
#[ORM\Entity]
#[ORM\Table(name: "students")]
class Student
{
#[ORM\Id]
#[ORM\Column(type: "integer")]
#[ORM\GeneratedValue]
#[ORM\Column(nullable: false)]
private $id;
#[ORM\Column(type: "string", length: 50, nullable: false)]
private $name;
#[ORM\Column(type: "string", length: 50, nullable: false)]
private $firstname;
#[ORM\Column(type: "integer", nullable: false)]
private $age;
// Getter pour l'id
public function getId()
{
return $this->id;
}
// Getter et setter pour le nom
public function getName()
{
return $this->name;
}
public function setName($name): void
{
$this->name = $name;
}
// Getter et setter pour le prénom
public function getFirstname()
{
return $this->firstname;
}
public function setFirstname($firstname): void
{
$this->firstname = $firstname;
}
// Getter et setter pour l'âge
public function getAge()
{
return $this->age;
}
public function setAge($age): void
{
$this->age = $age;
}
}