Categories
mySql PHP Slim Framework Tips & Tricks

Global site settings middleware for Slim Framework v3 with eav data table

Hi there,

I wrote this small middleware code which might help you if you want to store your settings in database and access them everywhere in your application. You can use it in twig template by just typing setting name (what ever you insert into your setting table ) for example {{site_logo}} or in any route.

Here is the middleware code:

app = $app;
    $this->view = $app->getContainer()->get('view');
    $this->pdo =  $app->getContainer()->get('pdo');
    if ( !$this->pdo instanceof PDO ) {
      throw new \RuntimeException (
        sprintf(
          '%s requires a PDO instance, app did not contain "PDO" key',
          __CLASS__
        )
      );
    }
  }
  public function __invoke( $request, $response, $next ) {
    $settings = $this->getSettings();
    if( $settings ) {
      foreach ( $settings as $row ) {
        $this->view->getEnvironment()->addGlobal(
          $row['setting'],
          $row['value']
        );
        $request->withAttribute(
          $row['setting'],
          $row['value']
        );
      }
      $response = $next( $request, $response );
    }
    return $response;
  }
  protected function getSettings() {
    try {
      $stmt = $this->pdo->query( 'SELECT setting, value, description FROM site_settings' );
      return $stmt->fetchAll();
    } catch ( PDOException $pe ) {
      return false;
    }
  }
}

add the middleware to all routes:

$app->add( new entity\SiteSettings( $app ) );

and use it in any route or in view:

<?php
$app->get('/en/admin', function ($request, $response, $args) {
    // Sample log message
    $this->logger->info("Slim-Skeleton '/' route");
    echo $request->getAttribute('site_name');

 });

 

and here is the sql table:

CREATE TABLE `site_settings` (
	`setting` VARCHAR(250) NOT NULL DEFAULT '' COLLATE 'utf8_unicode_ci',
	`value` VARCHAR(250) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
	`description` TINYTEXT NULL COLLATE 'utf8_unicode_ci',
	PRIMARY KEY (`setting`)
)
COLLATE='utf8_unicode_ci'
ENGINE=InnoDB
;