Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- $app->get('/content', AppControllersContentController::class);
- <?php
- namespace AppControllers;
- class ContentController
- {
- protected $container;
- // Passes the DIC to get the model.
- function __construct($container)
- {
- $this->container = $container;
- }
- function __invoke($request, $response, $args)
- {
- $datas = $this->container->get('contentModel');
- $args['content'] = $datas->testContent();
- // get the template renderer and pass response and datas to the template file.
- return $this->container->get('renderer')->render($response, 'content.php', $args);
- }
- <?php
- namespace AppModels;
- class Model
- {
- // Passes the DIC to get db later.
- function __construct($container)
- {
- $this->container = $container;
- }
- protected function executeQuery($sql, $params = null) {
- if ($params == null)
- {
- $result = $this->container->get('db')->query($sql); // direct execution
- } else {
- $result = $this->container->get('db')->prepare($sql); // prepared execution
- $result->execute($params);
- }
- return $result;
- }
- }
- <?php
- namespace AppModels;
- Class ContentModel extends Model
- {
- public function testContent()
- {
- $testDatas = "Hello world";
- return $testDatas;
- }
- public function getContent()
- {
- $sql = 'SELECT * FROM posts';
- $posts = $this->executeQuery($sql);
- return $posts;
- }
- }
- <?php
- use SlimApp;
- return function (App $app) {
- $container = $app->getContainer();
- // View renderer
- $container['renderer'] = function ($c) {
- $settings = $c->get('settings')['renderer'];
- return new SlimViewsPhpRenderer($settings['template_path']);
- };
- // Database
- $container['db'] = function ($c) {
- $db = $c['settings']['db'];
- $pdo = new PDO('mysql:host=' . $db['host'] . ';dbname=' . $db['dbname'],
- $db['user'], $db['pass']);
- $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
- return $pdo;
- };
- // Model data stored
- $container['contentModel'] = new AppModelsContentModel();
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement