<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Yii3  |  takeHo（たけほ）のへなちょこ台帳</title>
	<atom:link href="https://blog.takeho.com/tag/yii3/feed/" rel="self" type="application/rss+xml" />
	<link>https://blog.takeho.com</link>
	<description>いわゆる自由帳ってところです。</description>
	<lastBuildDate>Thu, 03 Jul 2025 09:41:07 +0000</lastBuildDate>
	<language>ja</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.6</generator>

<image>
	<url>https://blog.takeho.com/wp-content/uploads/2024/08/icon-150x150.png</url>
	<title>Yii3  |  takeHo（たけほ）のへなちょこ台帳</title>
	<link>https://blog.takeho.com</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Yii3ついに登場！Yii2からどう変わった？進化点と基本構造、サンプルを一挙解説</title>
		<link>https://blog.takeho.com/yii3-is-finally-here-evolution-basic-structure-and-samples-at-a-glance/</link>
					<comments>https://blog.takeho.com/yii3-is-finally-here-evolution-basic-structure-and-samples-at-a-glance/#respond</comments>
		
		<dc:creator><![CDATA[たけほ]]></dc:creator>
		<pubDate>Fri, 04 Jul 2025 11:26:00 +0000</pubDate>
				<category><![CDATA[Yii2]]></category>
		<category><![CDATA[DI]]></category>
		<category><![CDATA[PSR]]></category>
		<category><![CDATA[Yii3]]></category>
		<guid isPermaLink="false">https://blog.takeho.com/?p=1206</guid>

					<description><![CDATA[PHPの人気フレームワーク「Yii2」の後継として、長らく開発が続けられていた「Yii3」がついにリリース間近となりました。公式ガイド（https://yii3.netlify.app/guide.html）も整備されつ [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>PHPの人気フレームワーク「Yii2」の後継として、長らく開発が続けられていた「Yii3」がついにリリース間近となりました。<br>公式ガイド（<a class="" href="https://yii3.netlify.app/guide.html">https://yii3.netlify.app/guide.html</a>）も整備されつつあり、Yii2ユーザーやこれからPHPフレームワークを選ぼうとしている方にとって注目のタイミングです。</p>



<p>本記事では、Yii3で何が変わったのか、Yii2との違いやディレクトリ構造、実際にデータベースを使ったミニサンプルも交えて、実用的に解説します。</p>





<a rel="noopener" href="https://yii3.netlify.app/guide.html" title="Guide | Yii3" class="blogcard-wrap external-blogcard-wrap a-wrap cf" target="_blank"><div class="blogcard external-blogcard eb-left cf"><div class="blogcard-label external-blogcard-label"><span class="fa"></span></div><figure class="blogcard-thumbnail external-blogcard-thumbnail"><img decoding="async" src="https://s.wordpress.com/mshots/v1/https%3A%2F%2Fyii3.netlify.app%2Fguide.html?w=160&#038;h=90" alt="" class="blogcard-thumb-image external-blogcard-thumb-image" width="160" height="90" /></figure><div class="blogcard-content external-blogcard-content"><div class="blogcard-title external-blogcard-title">Guide | Yii3</div><div class="blogcard-snippet external-blogcard-snippet">Various Yii 3.0 related documentation</div></div><div class="blogcard-footer external-blogcard-footer cf"><div class="blogcard-site external-blogcard-site"><div class="blogcard-favicon external-blogcard-favicon"><img decoding="async" src="https://www.google.com/s2/favicons?domain=https://yii3.netlify.app/guide.html" alt="" class="blogcard-favicon-image external-blogcard-favicon-image" width="16" height="16" /></div><div class="blogcard-domain external-blogcard-domain">yii3.netlify.app</div></div></div></div></a>





  <div id="toc" class="toc tnt-number toc-center tnt-number border-element"><input type="checkbox" class="toc-checkbox" id="toc-checkbox-2"><label class="toc-title" for="toc-checkbox-2">目次</label>
    <div class="toc-content">
    <ol class="toc-list open"><li><a href="#toc1" tabindex="0">Yii2との主な違い・進化ポイント</a></li><li><a href="#toc2" tabindex="0">Yii3のディレクトリ構成</a></li><li><a href="#toc3" tabindex="0">Yii3での簡単なデータベース操作サンプル（MVC構成で作成）</a><ol><li><a href="#toc4" tabindex="0">ディレクトリ構成とファイル配置</a></li><li><a href="#toc5" tabindex="0">モデル（M） – src/Model/Post.php</a></li><li><a href="#toc6" tabindex="0">コントローラ（C） – src/Controller/SiteController.php</a></li><li><a href="#toc7" tabindex="0">ビュー（V） – src/View/site/index.php</a></li><li><a href="#toc8" tabindex="0">ルーティング設定 – config/routes.php</a></li><li><a href="#toc9" tabindex="0">アプリ設定 – config/web.php</a></li><li><a href="#toc10" tabindex="0">フロントコントローラ – public/index.php</a></li><li><a href="#toc11" tabindex="0">MySQL テーブル定義</a></li><li><a href="#toc12" tabindex="0">実行までの流れまとめ</a></li></ol></li><li><a href="#toc13" tabindex="0">補足：Yii3は「自由度の高いMVC」</a></li></ol>
    </div>
  </div>

<h2 class="wp-block-heading"><span id="toc1">Yii2との主な違い・進化ポイント</span></h2>



<figure class="wp-block-table"><table class="has-fixed-layout"><thead><tr><th>項目</th><th>Yii2</th><th>Yii3</th></tr></thead><tbody><tr><td>リリース形態</td><td>モノリシック構造</td><td>パッケージ分割（コンポーザ管理）</td></tr><tr><td>DI（依存性注入）</td><td>独自コンテナ</td><td>PSR-11準拠のDIコンテナ</td></tr><tr><td>イベントシステム</td><td>グローバル依存</td><td>より明確なスコープ管理</td></tr><tr><td>HTTP処理</td><td>Yii独自実装</td><td>PSR-7/PSR-15完全対応</td></tr><tr><td>テンプレートエンジン</td><td>PHPベース（Twig等も可）</td><td>Twig対応強化、Templateパッケージ分離</td></tr><tr><td>ルーティング</td><td>独自実装</td><td>PSR準拠、Middleware対応</td></tr><tr><td>テスト性</td><td>構造がやや閉じていた</td><td>モジュール化されテストしやすく</td></tr><tr><td>コマンドライン</td><td>yiiコマンド一体型</td><td>独立したパッケージに分離（symfony/console）</td></tr></tbody></table></figure>



<p>Yii3では、近年のPHP界のトレンドであるPSR準拠を徹底しており、<strong>モダンPHPと高い互換性</strong>を持ちながら設計されています。</p>



<h2 class="wp-block-heading"><span id="toc2">Yii3のディレクトリ構成</span></h2>



<p>Yii3の標準的なアプリケーション構造は以下のようになります。</p>



<pre class="wp-block-preformatted">myapp/<br>├── config/          ← アプリ設定（DIやルーティングなど）<br>├── public/          ← Web公開ディレクトリ（index.php）<br>├── runtime/         ← ログやキャッシュなどの一時ファイル<br>├── src/             ← アプリケーションの本体コード<br>│   └── Controller/<br>│   └── Middleware/<br>│   └── View/<br>├── tests/           ← PHPUnitベースのテストコード<br>├── vendor/          ← Composer依存<br>└── composer.json</pre>



<p>「config」や「src」にアプリロジックが集約されており、明確にMVCが分離されています。</p>



<h2 class="wp-block-heading"><span id="toc3">Yii3での簡単なデータベース操作サンプル（MVC構成で作成）</span></h2>



<p>このサンプルでは、次の機能を実装します。</p>



<blockquote class="wp-block-quote is-layout-flow wp-block-quote-is-layout-flow">
<p>「<code>post</code> テーブルの全件を取得して、一覧表示するWebページ」</p>
</blockquote>



<h3 class="wp-block-heading"><span id="toc4">ディレクトリ構成とファイル配置</span></h3>



<p>まず、以下のようにディレクトリ構成を整理します。Yii3では、<code>src/</code> がアプリケーションコードの中核です。</p>



<pre class="wp-block-code"><code>myapp/
├── config/
│   └── params.php
│   └── routes.php         ← ルーティング設定
│   └── web.php            ← DI・アプリ設定
├── src/
│   ├── Controller/
│   │   └── SiteController.php   ← コントローラ（C）
│   ├── Model/
│   │   └── Post.php             ← モデル（M）
│   ├── View/
│   │   └── site/
│   │       └── index.php        ← ビュー（V）
├── public/
│   └── index.php          ← フロントコントローラ
├── vendor/                ← Composer依存
└── composer.json</code></pre>



<h3 class="wp-block-heading"><span id="toc5">モデル（M） – src/Model/Post.php</span></h3>



<p>ActiveRecordを使用して、<code>post</code> テーブルに対応したモデルクラスを作成します。</p>



<pre class="wp-block-code"><code>&lt;?php
namespace App\Model;

use Yiisoft\ActiveRecord\ActiveRecord;

final class Post extends ActiveRecord
{
    public static function tableName(): string
    {
        return 'post';
    }
}</code></pre>



<h3 class="wp-block-heading"><span id="toc6">コントローラ（C） – src/Controller/SiteController.php</span></h3>



<p>データベースからデータを取得し、ビューに渡す役割を担います。</p>



<pre class="wp-block-code"><code>&lt;?php
namespace App\Controller;

use App\Model\Post;
use Yiisoft\Yii\View\ViewRenderer;
use Yiisoft\Router\CurrentRoute;

final class SiteController
{
    private ViewRenderer $view;

    public function __construct(ViewRenderer $view)
    {
        $this->view = $view->withControllerName('site');
    }

    public function index(): string
    {
        $posts = Post::find()->all(); // すべての投稿を取得
        return $this->view->render('index', &#91;'posts' => $posts]);
    }
}</code></pre>



<h3 class="wp-block-heading"><span id="toc7">ビュー（V） – src/View/site/index.php</span></h3>



<p>データをHTMLとして整形・表示するテンプレートファイルです。</p>



<pre class="wp-block-code"><code>&lt;h1>記事一覧&lt;/h1>

&lt;ul>
&lt;?php foreach ($posts as $post): ?>
    &lt;li>
        &lt;strong>&lt;?= htmlspecialchars($post->title) ?>&lt;/strong>&lt;br>
        &lt;?= nl2br(htmlspecialchars($post->content)) ?>
    &lt;/li>
&lt;?php endforeach; ?>
&lt;/ul></code></pre>



<h3 class="wp-block-heading"><span id="toc8">ルーティング設定 – config/routes.php</span></h3>



<p>リクエストURLとコントローラの対応関係を定義します。</p>



<pre class="wp-block-code"><code>&lt;?php

use Yiisoft\Router\Route;
use App\Controller\SiteController;

return &#91;
    Route::get('/')
        ->action(&#91;SiteController::class, 'index'])
];</code></pre>



<h3 class="wp-block-heading"><span id="toc9">アプリ設定 – config/web.php</span></h3>



<p>必要なパッケージや設定を読み込むファイルです。ここでDB接続なども設定します。</p>



<pre class="wp-block-code"><code>&lt;?php

use Yiisoft\Db\Connection\ConnectionInterface;
use Yiisoft\Db\Mysql\Connection;

return &#91;
    ConnectionInterface::class => static function () {
        return new Connection(
            dsn: 'mysql:host=localhost;dbname=yii3_demo',
            username: 'root',
            password: 'your_password',
        );
    },
];</code></pre>



<h3 class="wp-block-heading"><span id="toc10">フロントコントローラ – public/index.php</span></h3>



<p>アプリケーションのエントリーポイントです。</p>



<pre class="wp-block-code"><code>&lt;?php

declare(strict_types=1);

require dirname(__DIR__) . '/vendor/autoload.php';

use Yiisoft\Yii\Web\Application;
use Yiisoft\Yii\Web\Emitter\SapiEmitter;

$container = require dirname(__DIR__) . '/config/web.php';

$app = new Application($container);

$response = $app->handle(
    $_SERVER&#91;'REQUEST_METHOD'],
    $_SERVER&#91;'REQUEST_URI']
);

(new SapiEmitter())->emit($response);</code></pre>



<h3 class="wp-block-heading"><span id="toc11">MySQL テーブル定義</span></h3>



<pre class="wp-block-code"><code>CREATE TABLE post (
    id INT AUTO_INCREMENT PRIMARY KEY,
    title VARCHAR(255) NOT NULL,
    content TEXT NOT NULL
);</code></pre>



<h3 class="wp-block-heading"><span id="toc12">実行までの流れまとめ</span></h3>



<ol class="wp-block-list">
<li>MySQLで <code>post</code> テーブルを作成する</li>



<li><code>composer install</code> で依存パッケージを取得</li>



<li><code>php -S localhost:8080 -t public</code> で開発サーバを起動</li>



<li>ブラウザで <code>http://localhost:8080</code> にアクセス</li>
</ol>



<h2 class="wp-block-heading"><span id="toc13">補足：Yii3は「自由度の高いMVC」</span></h2>



<p>Yii3は、Laravelのような「レールに乗った」MVCよりも、より<strong>柔軟で明示的なアーキテクチャ</strong>を採用しています。自分で組み立てる分、学習コストはやや高いかもしれませんが、カスタマイズ性と保守性に優れた構成です。</p>



<p>この構成に沿えば、<strong>MVCモデルの設計思想を維持しつつ、Yii3のモダンな利点</strong>を活かしたWebアプリを構築できます。<br>今後はフォームバリデーション、APIレスポンス、ログイン機能など、より実践的なトピックも記事化していきます。</p>
]]></content:encoded>
					
					<wfw:commentRss>https://blog.takeho.com/yii3-is-finally-here-evolution-basic-structure-and-samples-at-a-glance/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
