序章

Silexは、Symfony2コンポーネント上に構築されたPHPマイクロフレームワークです。 小さなウェブサイトや大きなアプリケーションを同様に構築するために使用できます。 簡潔で、拡張可能で、テスト可能です。

このチュートリアルでは、Silexをダウンロードして構成することから始めます。 次に、基本的なSilexアプリケーションの作成方法を学習します。

Composerを使用して、人気のあるPHPパッケージマネージャーであるSilexをインストールします。 Composerの詳細については、このチュートリアルを参照してください。 このチュートリアルを終了すると、完全に機能するブログサイトができあがります。

注:このチュートリアルはUbuntuでテストされましたが、他のLinuxディストリビューションでも同様に機能するはずです。 リンクはUbuntuチュートリアルを参照していますが、サーバーをセットアップし、LAMPスタックとGitをインストールするための適切なガイドを見つけてください。

前提条件

これらの前提条件を完了してください。

ステップ1—Silexをインストールする

このセクションでは、Composerを使用してSilexをインストールします。 まず、作業ディレクトリをApacheドキュメントルートに変更します。 /var/www/html:

cd /var/www/html

次に、このフォルダのデフォルトの内容を削除します。

sudo rm /var/www/html/index.html

次に、に移動します /var/www すべてのファイルを公開しないようにディレクトリ:

cd /var/www

次に、Composerをダウンロードします。

sudo curl -sS https://getcomposer.org/installer | sudo php

次に、Composerファイルを作成して編集します composer.json:

sudo nano composer.json

このファイルに、次の内容を追加します。

{
    "require": {
        "silex/silex": "~1.2"
    }
}

これで、Composerに依存関係としてSilexバージョン1.2をダウンロードするように指示しました。 ダウンロードを開始するには、次のコマンドを実行します。

sudo php composer.phar update

これで、ComposerはSilexとその依存関係をダウンロードします。 これには数秒かかる場合があります。

ステップ2—Silexのブートストラップ

このセクションでは、必要なファイルを含めてアプリケーションを作成することにより、Silexをブートストラップします。 開始するには、ファイルを編集します /var/www/html/index.php:

sudo nano /var/www/html/index.php

このファイルに、次の基本的な内容を追加します。

<?php
require_once __DIR__.'/../vendor/autoload.php'; // Add the autoloading mechanism of Composer

$app = new Silex\Application(); // Create the Silex application, in which all configuration is going to go

// Section A
// We will later add the configuration, etc. here


// This should be the last line
$app->run(); // Start the application, i.e. handle the request
?>

このチュートリアル全体を通して、このファイルに構成情報やその他のデータを追加します。 追加するすべての新しい行が追加されます Section A、 間に $app = new Silex\Application();$app->run(); 行。

同じファイルで、 /var/www/html/index.php アプリケーションの開発時に役立つデバッグをオンにします。 セクションAに次の行を追加します。

$app['debug'] = true;

ステップ3-ブログアプリケーションを作成する

このセクションでは、サンプルのブログアプリケーションを作成します。 代わりに独自のアプリケーションに集中したい場合は、Silexドキュメントをご覧ください。

サンプルのブログアプリケーションを作成します。 データベースを利用しませんが、DoctrineServiceProviderドキュメントを参照することで比較的簡単に変換できます。

Twigテンプレートエンジンの追加

まず、別の依存関係Twigを追加することから始めます。 Twigは、Symfonyフレームワークでも使用されるテンプレートエンジンです。 アプリケーションのテンプレートを提供します。 追加するには、編集します composer.json:

sudo nano /var/www/composer.json

次に、の新しい依存関係行を追加します twig、下に赤で示されています。 前の行のコンマを忘れないでください:

{
    "require": {
        "silex/silex": "~1.2",
        "twig/twig": ">=1.8,<2.0-dev"
    }
}

次に、Composerの依存関係を更新します。

sudo php composer.phar update

mod_rewriteを有効にする

次に、Webサーバー(この場合はApache)を構成する必要があります。

まず、有効になっていることを確認します mod_rewrite 変更を許可したこと .htaccess ファイル。 プロセスはこのチュートリアルで説明されていますが、Ubuntu14.04のデフォルトの仮想ホストが /var/www/html それよりも /var/www.

モジュールを有効にした後(リンクされたチュートリアルで説明されているように)、次の行を /etc/apache2/sites-available/000-default.conf ファイル:

sudo vim /etc/apache2/sites-available/000-default.conf
<Directory /var/www/html/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
</Directory>

次に、を作成して編集します .htaccess ファイル:

sudo nano /var/www/html/.htaccess

このファイルに、次の内容を追加します。

<IfModule mod_rewrite.c>
    Options -MultiViews

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [QSA,L]
</IfModule>

これにより、存在しないファイルに対するリクエストがアプリケーションを指すようになり、アプリケーションがルーティングを実行できるようになります。

ブログコンテンツの作成

いくつかの記事を追加するために、タイトル、内容、著者、発行日を含む配列を作成します。 これは、拡張するコンテナオブジェクトを使用して、アプリケーションオブジェクトに格納できます。 コンテナオブジェクトは複数のオブジェクトを保持でき、アプリケーション内の他のすべてのオブジェクトで再利用できます。 これを行うには、以下を追加します Section A/var/www/html/index.php

sudo nano /var/www/html/index.php

次の内容を追加します。

$app['articles'] = array(
    array(
        'title'    => 'Lorem ipsum dolor sit amet',
        'contents' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mollis vestibulum ultricies. Sed sit amet sagittis nisl. Nulla leo metus, efficitur non risus ut, tempus convallis sem. Mauris pharetra sagittis ligula pharetra accumsan. Cras auctor porta enim, a eleifend enim volutpat vel. Nam volutpat maximus luctus. Phasellus interdum elementum nulla, nec mollis justo imperdiet ac. Duis arcu dolor, ultrices eu libero a, luctus sollicitudin diam. Phasellus finibus dictum turpis, nec tincidunt lacus ullamcorper et. Praesent laoreet odio lacus, nec lobortis est ultrices in. Etiam facilisis elementum lorem ut blandit. Nunc faucibus rutrum nulla quis convallis. Fusce molestie odio eu mauris molestie, a tempus lorem volutpat. Sed eu lacus eu velit tincidunt sodales nec et felis. Nullam velit ex, pharetra non lorem in, fringilla tristique dolor. Mauris vel erat nibh.',
        'author'   => 'Sammy',
        'date'     => '2014-12-18',
    ),
    array(
        'title'    => 'Duis ornare',
        'contents' => 'Duis ornare, odio sit amet euismod vulputate, purus dui fringilla neque, quis eleifend purus felis ut odio. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque bibendum pretium ante, eu aliquet dolor feugiat et. Pellentesque laoreet est lectus, vitae vulputate libero sollicitudin consequat. Vivamus finibus interdum egestas. Nam sagittis vulputate lacus, non condimentum sapien lobortis a. Sed ligula ante, ultrices ut ullamcorper nec, facilisis ac mi. Nam in vehicula justo. In hac habitasse platea dictumst. Duis accumsan pellentesque turpis, nec eleifend ex suscipit commodo.',
        'author'   => 'Sammy',
        'date'     => '2014-11-08',
    ),
);

これらの記事は、アプリケーションのどこでも再利用でき、さらに自分で追加することもできます。 実際のWebサイトの場合、データベースを使用することをお勧めします。

ルーティング

基本的に、ルーティングは次のようなURLをマップします http://www.example.com/ / に移動し、それに関連付けられた機能を実行します。 基本ルートを追加するには、以下を追加します Section A/var/www/html/index.php:

sudo nano /var/www/html/index.php

コンテンツ:

$app->get('/', function (Silex\Application $app)  { // Match the root route (/) and supply the application as argument
    $output = '';
    foreach ($app['articles'] as $article) { // Create a basic list of article titles
        $output .= $article['title'];
        $output .= '<br />';
    }

    return $output; // Return it to so it gets displayed by the browser
});

今、あなたが訪問するとき http://your_server_ip、記事のタイトルのリストを表示する必要があります。

テンプレート

私たちのウェブサイトは正しい出力を表示するようになりましたが、見栄えはよくありません。 これを修正するために、Twigを使用します。

まず、Silexでは、Twigをサービスプロバイダーとして登録する必要があります。これは、基本的に、アプリケーションの特定の部分を別のアプリケーションで再利用する方法です。 Twigを登録するには、これを追加します section A:

sudo nano /var/www/html/index.php

コンテンツ:

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__.'/../templates', // The path to the templates, which is in our case points to /var/www/templates
));

これで、Twigテンプレートエンジンを利用できるようになりました。 これを行うには、 $app->get('/', function (Silex\Application $app) { }); ブロック、のルートを定義します /、ここに表示されているものと一致します。 新しい行はで表示されます。

$app->get('/', function (Silex\Application $app)  { // Match the root route (/) and supply the application as argument
    return $app['twig']->render( // Render the page index.html.twig
        'index.html.twig',
        array(
            'articles' => $app['articles'], // Supply arguments to be used in the template
        )
    );
});

変更を保存してファイルを閉じます。

それでは、を作成しましょう index.html.twig テンプレート。 ディレクトリを作成してから、ファイルを作成して開きます base.html.twig:

sudo mkdir /var/www/templates
sudo nano /var/www/templates/base.html.twig

このファイルがベーステンプレートになります。つまり、他のすべてのテンプレートがこのファイルから継承されるため、すべてのテンプレートに基本を追加する必要はありません。 このファイルに、次の内容を追加します。

<!doctype html>
<html>
<head>
    <title>{% block title %}Blog{% endblock %}</title>
</head>
<body>
{% block body %}

{% endblock body %}
</body>
</html>

このファイルには、2つのブロックが含まれています。 サブテンプレートでブロックをオーバーライドして、コンテンツを提供できます。 と呼ばれるブロック title 単一の記事ページのタイトルを提供するために使用されます。 ブロック body すべてのコンテンツを表示するために使用されます。

変更を保存します。

次に、ファイルを作成して編集します /var/www/templates/index.html.twig:

sudo nano /var/www/templates/index.html.twig

次の内容を追加します。

{% extends 'base.html.twig' %}
{% block body %}
    <h1>
        Blog index
    </h1>

    {% for article in articles %}
        <article>
            <h1>{{ article.title }}</h1>
            <p>{{ article.contents }}</p>
            <p><small>On {{ article.date }} by {{ article.author }}</small></p>
        </article>
    {% endfor %}
{% endblock %}

まず、テンプレートを拡張することを指定します base.html.twig. その後、親テンプレートで定義されたブロックのオーバーライドを開始できます。 このテンプレートでは、ブロックのみをオーバーライドします body、すべての記事を表示するループを作成します。

今すぐ訪問 http://your_server_ip; すべての投稿のインデックスが表示されます。

単一の投稿用の別のコントローラー

次に、単一の投稿を表示する別のコントローラーを追加します。 投稿は、配列インデックスによって照合されます。 開ける /var/www/html/index.php また:

sudo nano /var/www/html/index.php

これをに追加 Section A、これにより、個々の記事のページを表示できるようになります。

$app->get('/{id}', function (Silex\Application $app, $id)  { // Add a parameter for an ID in the route, and it will be supplied as argument in the function
    if (!array_key_exists($id, $app['articles'])) {
        $app->abort(404, 'The article could not be found');
    }
    $article = $app['articles'][$id];
    return $app['twig']->render(
        'single.html.twig',
        array(
            'article' => $article,
        )
    );
})
    ->assert('id', '\d+') // specify that the ID should be an integer
    ->bind('single'); // name the route so it can be referred to later in the section 'Generating routes'

変更を保存します。 次に、ファイルを作成して編集します /var/www/templates/single.html.twig:

sudo nano /var/www/templates/single.html.twig

次の内容を追加します。

{% extends 'base.html.twig' %}
{% block title %}{{ article.title }}{% endblock %}
{% block body %}
    <h1>
        {{ article.title }}
    </h1>
    <p>{{ article.contents }}</p>
    <p><small>On {{ article.date }} by {{ article.author }}</small></p>
{% endblock %}

このテンプレートでは、 title ブロックして記事のタイトルを表示します。 The body ブロックは前者とほとんど同じに見えます body ブロックするので、かなり自明のはずです。

あなたが今訪問する場合 http://your_server_ip/0 また http://your_server_ip/1、記事を表示する必要があります:

ただし、次のような存在しないIDにアクセスした場合 http://your_server_ip/2 この例では、エラーページが表示されます。

ルートの生成

次に、ホームページから単一の記事ビューにリンクを追加し、記事からホームページに戻ります。 Silexには、Symfonyコンポーネントを使用してルートを生成する機能があります。 サービスプロバイダーとして提供されているため、最初に追加する必要があります Section A. 開ける /var/www/html/index.php:

sudo nano /var/www/html/index.php

以下を追加します Section A:

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

これにより、URLジェネレータサービスを利用できるようになります。 シングルビューコントローラを作成したとき、すでに名前付きルートを追加しました。 これは、次の行を使用して行われました。

->bind('single'); // name the route so it can be referred to later in the section 'Generating routes'

次に、ルートをホームページにバインドする必要もあります。 これを行うには、を追加します ->bind('index') このブロックの最後、最後のセミコロンの直前にルーティングします。 変更はでマークされています:

$app->get('/', function (Silex\Application $app)  { // Match the root route (/) and supply the application as argument
    return $app['twig']->render(
        'index.html.twig',
        array(
            'articles' => $app['articles'],
        )
    );
})->bind('index');

次に、実際にURLを生成する必要があります。 開ける /var/www/templates/index.html.twig:

sudo nano /var/www/templates/index.html.twig

次に、以下を変更します <h1> 以下に示すように、行:

{% extends 'base.html.twig' %}
{% block body %}
    <h1>
        Blog index
    </h1>

    {% for article in articles %}
        <article>
            <h1><a href="{{ app.url_generator.generate('single', { id: loop.index0 }) }}">{{ article.title }}</a></h1>
            <p>{{ article.contents }}</p>
            <p><small>On {{ article.date }} by {{ article.author }}</small></p>
        </article>
    {% endfor %}
{% endblock %}

これにより、記事のタイトルから個々の記事ページへのリンクが作成されます。 The app.url_generator 登録したサービスを指します。 The generate 関数は2つのパラメータを取ります:ルート名、 single この場合、ルートのパラメータ(この場合はIDのみ)。 loop.index0 ループ内の0インデックスのインデックスを参照します。 したがって、最初のアイテムがループされると、それは 0; 2番目のアイテムがループされると、 1、など。

単一ページテンプレートのインデックスページを参照するためにも同じことができます。

sudo nano /var/www/templates/single.html.twig

以下を追加します <p> リンクを作成する行:

{% extends 'base.html.twig' %}
{% block title %}{{ article.title }}{% endblock %}
{% block body %}
    <h1>
        {{ article.title }}
    </h1>
    <p>{{ article.contents }}</p>
    <p><small>On {{ article.date }} by {{ article.author }}</small></p>

    <p><a href="{{ app.url_generator.generate('index') }}">Back to homepage</a></p>
{% endblock %}

これはかなり自明のはずです。

それでおしまい! 再度ウェブサイトにアクセスしてください。 http://your_server_ip/. 記事のタイトルをクリックしてその記事のページにアクセスし、記事の下部にあるリンクを使用してホームページに戻ることができるはずです。

完全なindex.phpファイル

参考までに、これが最終的なものです /var/www/html/index.php ファイルは次のようになります。

<?php
require_once __DIR__.'/../vendor/autoload.php'; // Add the autoloading mechanism of Composer

$app = new Silex\Application(); // Create the Silex application, in which all configuration is going to go



// Section A
// We will later add the configuration, etc. here

$app['debug'] = true;
$app['articles'] = array(
    array(
        'title'    => 'Lorem ipsum dolor sit amet',
        'contents' => 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean mollis vestibulum ultricies. Sed sit amet sagittis nisl. Nulla leo metus, efficitur non risus ut, tempus convallis sem. Mauris pharetra sagittis ligula pharetra accumsan. Cras auctor porta enim, a eleifend enim volutpat vel. Nam volutpat maximus luctus. Phasellus interdum elementum nulla, nec mollis justo imperdiet ac. Duis arcu dolor, ultrices eu libero a, luctus sollicitudin diam. Phasellus finibus dictum turpis, nec tincidunt lacus ullamcorper et. Praesent laoreet odio lacus, nec lobortis est ultrices in. Etiam facilisis elementum lorem ut blandit. Nunc faucibus rutrum nulla quis convallis. Fusce molestie odio eu mauris molestie, a tempus lorem volutpat. Sed eu lacus eu velit tincidunt sodales nec et felis. Nullam velit ex, pharetra non lorem in, fringilla tristique dolor. Mauris vel erat nibh.',
        'author'   => 'Sammy',
        'date'     => '2014-12-18',
    ),
    array(
        'title'    => 'Duis ornare',
        'contents' => 'Duis ornare, odio sit amet euismod vulputate, purus dui fringilla neque, quis eleifend purus felis ut odio. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque bibendum pretium ante, eu aliquet dolor feugiat et. Pellentesque laoreet est lectus, vitae vulputate libero sollicitudin consequat. Vivamus finibus interdum egestas. Nam sagittis vulputate lacus, non condimentum sapien lobortis a. Sed ligula ante, ultrices ut ullamcorper nec, facilisis ac mi. Nam in vehicula justo. In hac habitasse platea dictumst. Duis accumsan pellentesque turpis, nec eleifend ex suscipit commodo.',
        'author'   => 'Sammy',
        'date'     => '2014-11-08',
    ),
);

$app->get('/', function (Silex\Application $app)  { // Match the root route (/) and supply the application as argument
    return $app['twig']->render( // Render the page index.html.twig
        'index.html.twig',
        array(
            'articles' => $app['articles'], // Supply arguments to be used in the template
        )
    );
})->bind('index');

$app->register(new Silex\Provider\TwigServiceProvider(), array(
    'twig.path' => __DIR__.'/../templates', // The path to the templates, which is in our case points to /var/www/templates
));

$app->get('/{id}', function (Silex\Application $app, $id)  { // Add a parameter for an ID in the route, and it will be supplied as argument in the function
    if (!array_key_exists($id, $app['articles'])) {
        $app->abort(404, 'The article could not be found');
    }
    $article = $app['articles'][$id];
    return $app['twig']->render(
        'single.html.twig',
        array(
            'article' => $article,
        )
    );
})
    ->assert('id', '\d+') // specify that the ID should be an integer
    ->bind('single'); // name the route so it can be referred to later in the section 'Generating routes'

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




// This should be the last line
$app->run(); // Start the application, i.e. handle the request
?>

結論

Silexを使用して簡単なブログアプリケーションを作成しました。 データベースとの結合から始めて、さらに拡張することができます。 ただし、これはこのチュートリアルの範囲外です。 公式ドキュメントは非常に役立つ可能性があり、Silexを引き続き使用する場合は、必ず読む必要があります。

Silexが小さすぎる場合は、チュートリアルがここにあるSymfonyフレームワークの使用を検討する必要があります。