Silex

-

The PHP Microframework

Was ist Silex?

  • PHP Microframework
    "standing on the shoulders of giants"
  • Basiert auf Symfony Komponenten
  • Einfache Installation über Composer
  • MIT Lizenz
  • http://silex.sensiolabs.org

Was Silex nicht hat...

  • Ein CLI Tool
  • Features, die externe Dateien benötigen
    (XML/YML Konfigs)
  • Annotations

Warum Silex?

  • Full-Stack Framework Overkill für simple Tasks
    • Routes => Controllers
    • Silex != Symfony
  • Kompakt
  • Erweiterbar
  • Testbar
$ curl -sS https://getcomposer.org/installer | php

Installieren über Composer

{
  "name": "neusta/hello-silex",
  "require": {
    "php": ">=5.3.3",
    "silex/silex": "~1.2"
  }
}
$ php composer.phar install

 oder

$ composer install

App Struktur

  • composer.json
  • composer.lock
  • vendor
    • silex
  • src
    • <my-classes>
  • web
    • index.php

Quick Win

$ composer create-project fabpot/silex-skeleton

Features durch Provider

  • Provider erweitern die Funktionen der App
  • Alles läuft über den DI-Container Pimple
  • Große Provider Community
    • wie bei Symfony Bundles

Core Services

  • Request
  • Routes
  • ControllerCollection
  • EventDispatcher
  • Logger

Core ServiceProvider

  • Twig
  • URL Generator
  • Session
  • Validator
  • Form
  • HTTP Cache
  • HTTP Fragments
  • Security
  • Remember Me
  • Swiftmailer
  • Monolog
  • i18n
  • Serializer
  • Doctrine

Beispiel: Sessions

/* Add session support */

$app->register(new Silex\Provider\SessionProvider());

/* Save something in the session */

$app['session']->set('user', ['username' => 'johndoe']);

/* Fetch something in the session */

$user = $ap['session']->get('user');

Beispiel: Twig Templates

/* Add twig support */

$app->register(new Silex\Provider\TwigServiceProvider(), [
    'twig.path' => __DIR__ . '/../templates',
]);

/* Add controller to the app */

$app->get('/', function() use ($app) {
    return $app['twig']->render(
        'index.html.twig', 
        ['foo' => 'bar']
    );
})->bind('homepage');

Beispiel: Doctrine DBAL

/* Add doctrine dbal support */

$app->register(new Silex\Provider\DoctrineServiceProvider(), 
    [
        'db.options' => array(
            'driver'   => 'pdo_sqlite',
            'path'     => __DIR__.'/app.db',
    ],
));

/* Execute query */

$data = $app['db']->fetchAssoc(
    'SELECT * FROM table WHERE id = :id',
    ['id' => 1]
);

Bespiel: Mini JSON API

$app->get('/todo/{id}', function ($id) use ($app) {
    $sql = 'SELECT * FROM todo WHERE id = :id';
    $todo = $app['db']->fetchAssoc(
        $sql, 
        ['id' => (int)$id]
    );

    if (!$todo) {
        $app->abort(
            404, 
            sprintf('Todo %s does not exists.', $id)
        );
    }

    return $app->json($todo);
});

 A simple PHP Dependency Injection Container

Standalone Pimple

$ ./composer.phar require pimple/pimple ~3.0

  oder sogar als PHP C Extension

$ cd ext/pimple
$ phpize
$ ./configure
$ make
$ make install

Pimple ist simpel

use Pimple\Container;

$container = new Container();

Service

// define some services
$container['session_storage'] = function ($c) {
    return new SessionStorage('SESSION_ID');
};

$container['session'] = function ($c) {
    return new Session($c['session_storage']);
};

// get the session object
$session = $container['session'];

Singleton

Factory

$container['session'] = $container->factory(function ($c) {
    return new Session($c['session_storage']);
});

Neue Instanzen

Parameter

// define some parameters
$container['cookie_name'] = 'SESSION_ID';
$container['session_storage_class'] = 'SessionStorage';

// and use it
$container['session_storage'] = function ($c) {
    return new $c['session_storage_class']($c['cookie_name']);
};

Read-only Parameter

$container['random_func'] = $container->protect(function () {
    return rand();
});

Services erweitern

$container['session_storage'] = function ($c) {
    return new $c['session_storage_class']($c['cookie_name']);
};

$container->extend('session_storage', function ($storage, $c) {
    $storage->...();

    return $storage;
};

Auf Funktion zugreifen

$container['session'] = function ($c) {
    return new Session($c['session_storage']);
};

$sessionFunction = $container->raw('session');

Provider

use Pimple\Container;

class FooProvider implements Pimple\ServiceProviderInterface
{
    public function register(Container $pimple)
    {
        $pimple['foo'] = 'bar'
    }
}

// ... use it

$pimple->register(new FooProvider());

Eigener Container

use Pimple\Container as Pimple;

class MyContainer extends Pimple
{
    public function __construct() {

        parent::__construct([
            'foo' => 'bar'
        ]);

        $this->register(new FooProvider());        
    }
}

Provider in Silex

interface ServiceProviderInterface
{
    // executed after registering the Provider
    public function register(Application $app);

    // executed on $app->run();
    public function boot(Application $app);
}

Wo macht Silex Sinn?

  • Simple Anwendungen
  • RESTful APIs
  • Silex kann durchaus Symfony ersetzen

Viel Spaß

Silex - The PHP Microframework

By Ole Rößner

Silex - The PHP Microframework

  • 1,080