Commit 66960342 by Nobuo Kihara

Merge branch 'master' into docs-guide-ja-structure-revised

parents d148fee1 96c6d14a
Yii 2.0 公式ガイド
==================
決定版 Yii 2.0 ガイド
=====================
このチュートリアルは [Yii ドキュメント規約](http://www.yiiframework.com/doc/terms/) の下に
リリースされています。
このチュートリアルは [Yii ドキュメント規約](http://www.yiiframework.com/doc/terms/) の下にリリースされています。
All Rights Reserved.
......@@ -65,11 +64,11 @@ All Rights Reserved.
* [プロパティ](concept-properties.md)
* [イベント](concept-events.md)
* [ビヘイビア](concept-behaviors.md)
* [コンフィギュレーション](concept-configurations.md)
* [構成情報](concept-configurations.md)
* [エイリアス](concept-aliases.md)
* [クラスのオートロード](concept-autoloading.md)
* [サービスロケータ](concept-service-locator.md)
* [依存注入コンテナ](concept-di-container.md)
* [依存注入コンテナ](concept-di-container.md)
データベースの取り扱い
......@@ -102,8 +101,8 @@ All Rights Reserved.
* **TBD** [並べ替え](output-sorting.md)
* [データプロバイダ](output-data-providers.md)
* [データウィジェット](output-data-widgets.md)
* [クライアントスクリプトを使](output-client-scripts.md)
* [テーマを使う](output-theming.md)
* [クライアントスクリプトを](output-client-scripts.md)
* [テーマ](output-theming.md)
セキュリティ
......@@ -169,7 +168,7 @@ RESTful ウェブサービス
* [国際化](tutorial-i18n.md)
* [メール](tutorial-mailing.md)
* [パフォーマンスチューニング](tutorial-performance-tuning.md)
* **TBD** [共有ホスト環境](tutorial-shared-hosting.md)
* [共有ホスト環境](tutorial-shared-hosting.md)
* [テンプレートエンジン](tutorial-template-engines.md)
* [サードパーティのコードを扱う](tutorial-yii-integration.md)
......@@ -177,14 +176,14 @@ RESTful ウェブサービス
ウィジェット
------------
* GridView: link to demo page
* ListView: link to demo page
* DetailView: link to demo page
* ActiveForm: link to demo page
* Pjax: link to demo page
* Menu: link to demo page
* LinkPager: link to demo page
* LinkSorter: link to demo page
* GridView: **TBD** link to demo page
* ListView: **TBD** link to demo page
* DetailView: **TBD** link to demo page
* ActiveForm: **TBD** link to demo page
* Pjax: **TBD** link to demo page
* Menu: **TBD** link to demo page
* LinkPager: **TBD** link to demo page
* LinkSorter: **TBD** link to demo page
* [Bootstrap ウィジェット](widget-bootstrap.md)
* [Jquery UI ウィジェット](widget-jui.md)
......
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xmlns:yed="http://www.yworks.com/xml/yed/3" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd">
<!--Created by yEd 3.13-->
<key for="graphml" id="d0" yfiles.type="resources"/>
<key attr.name="Description" attr.type="string" for="graph" id="d0"/>
<key for="port" id="d1" yfiles.type="portgraphics"/>
<key for="port" id="d2" yfiles.type="portgeometry"/>
<key for="port" id="d3" yfiles.type="portuserdata"/>
<key attr.name="url" attr.type="string" for="node" id="d4"/>
<key attr.name="description" attr.type="string" for="node" id="d5"/>
<key for="node" id="d6" yfiles.type="nodegraphics"/>
<key attr.name="Description" attr.type="string" for="graph" id="d7"/>
<key for="graphml" id="d7" yfiles.type="resources"/>
<key attr.name="url" attr.type="string" for="edge" id="d8"/>
<key attr.name="description" attr.type="string" for="edge" id="d9"/>
<key for="edge" id="d10" yfiles.type="edgegraphics"/>
<graph edgedefault="directed" id="G">
<data key="d7"/>
<data key="d0"/>
<node id="n0" yfiles.foldertype="group">
<data key="d4"/>
<data key="d6">
......@@ -49,7 +49,7 @@
<y:Geometry height="30.0" width="324.9258883570935" x="-1249.511914911339" y="-169.79793039957679"/>
<y:Fill color="#FFFFFF" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="custom" textColor="#000000" visible="true" width="292.0" x="16.46294417854665" y="5.6494140625">アプリケーションのコンフィギュレーションをロード<y:LabelModel>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="custom" textColor="#000000" visible="true" width="208.0" x="58.46294417854665" y="5.6494140625">アプリケーションの構成情報をロード<y:LabelModel>
<y:SmartNodeLabelModel distance="4.0"/>
</y:LabelModel>
<y:ModelParameter>
......@@ -375,8 +375,7 @@
<y:Path sx="0.0" sy="0.0" tx="0.0" ty="0.0"/>
<y:LineStyle color="#666666" type="line" width="2.0"/>
<y:Arrows source="none" target="standard"/>
<y:EdgeLabel alignment="center" backgroundColor="#99CCFF" configuration="AutoFlippingLabel" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasLineColor="false" height="33.40234375" modelName="custom" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" visible="true" width="136.0" x="-145.73495249688403" y="70.83422851562506">コンフィギュレーション
配列<y:LabelModel>
<y:EdgeLabel alignment="center" backgroundColor="#99CCFF" configuration="AutoFlippingLabel" distance="2.0" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasLineColor="false" height="18.701171875" modelName="custom" preferredPlacement="anywhere" ratio="0.5" textColor="#000000" visible="true" width="76.0" x="-115.73495249688426" y="78.18481445312506">構成情報配列<y:LabelModel>
<y:SmartEdgeLabelModel autoRotationEnabled="false" defaultAngle="0.0" defaultDistance="10.0"/>
</y:LabelModel>
<y:ModelParameter>
......@@ -507,7 +506,7 @@
</data>
</edge>
</graph>
<data key="d0">
<data key="d7">
<y:Resources/>
</data>
</graphml>
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:y="http://www.yworks.com/xml/graphml" xmlns:yed="http://www.yworks.com/xml/yed/3" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd">
<!--Created by yEd 3.13-->
<key for="graphml" id="d0" yfiles.type="resources"/>
<key attr.name="Description" attr.type="string" for="graph" id="d0"/>
<key for="port" id="d1" yfiles.type="portgraphics"/>
<key for="port" id="d2" yfiles.type="portgeometry"/>
<key for="port" id="d3" yfiles.type="portuserdata"/>
<key attr.name="url" attr.type="string" for="node" id="d4"/>
<key attr.name="description" attr.type="string" for="node" id="d5"/>
<key for="node" id="d6" yfiles.type="nodegraphics"/>
<key attr.name="Description" attr.type="string" for="graph" id="d7"/>
<key for="graphml" id="d7" yfiles.type="resources"/>
<key attr.name="url" attr.type="string" for="edge" id="d8"/>
<key attr.name="description" attr.type="string" for="edge" id="d9"/>
<key for="edge" id="d10" yfiles.type="edgegraphics"/>
<graph edgedefault="directed" id="G">
<data key="d7"/>
<data key="d0"/>
<node id="n0">
<data key="d6">
<y:SVGNode>
......@@ -370,7 +370,7 @@
<y:Geometry height="30.0" width="169.93387606143483" x="307.6574954986572" y="262.00096702575684"/>
<y:Fill color="#FFFFFF" transparent="false"/>
<y:BorderStyle color="#000000" type="line" width="1.0"/>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="custom" textColor="#000000" visible="true" width="160.0" x="4.966938030717415" y="5.6494140625">アプリのコンフィグをロード<y:LabelModel>
<y:NodeLabel alignment="center" autoSizePolicy="content" fontFamily="Dialog" fontSize="12" fontStyle="plain" hasBackgroundColor="false" hasLineColor="false" height="18.701171875" modelName="custom" textColor="#000000" visible="true" width="148.0" x="10.966938030717415" y="5.6494140625">アプリの構成情報をロード<y:LabelModel>
<y:SmartNodeLabelModel distance="4.0"/>
</y:LabelModel>
<y:ModelParameter>
......@@ -650,7 +650,7 @@
</data>
</edge>
</graph>
<data key="d0">
<data key="d7">
<y:Resources>
<y:Resource id="1">&lt;?xml version="1.0" encoding="utf-8"?&gt;
&lt;svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
......
......@@ -3,7 +3,7 @@ Yii とは何か
Yii は現代的なウェブアプリケーションを迅速に開発するための、高性能な、コンポーネントベースの PHP フレームワークです。
Yii という名前 (`イー` すなわち `[ji:]` と発音します) は、中国語では「易」であり、「シンプルかつ進化的」であることを意味します。
また **Yes It Is**省略形であると考えることも出来ます。
また **Yes It Is**アクロニム(頭字語)であると考えることも出来ます。
Yii は何に向いているか
......@@ -17,20 +17,20 @@ Yii は汎用的なウェブプログラミングフレームワークです。
Yii を他のフレームワークと比べるとどうか?
-----------------------------------------
あなたが既に他のフレームワークに親しんでいる場合は、Yii を比較するとどうなるのかを知りたいと思うでしょう:
あなたが既に他のフレームワークに親しんでいる場合は、Yii を比較するとどうなるのかを知りたいと思うでしょう
- ほとんどの PHP フレームワーク同様、Yii は MVC (Model-View-Controller) デザインパターンを実装し、このパターンに基づいたコードの組織化を進しています。
- ほとんどの PHP フレームワーク同様、Yii は MVC (Model-View-Controller) デザインパターンを実装し、このパターンに基づいたコードの組織化を進しています。
- Yii は、コードはシンプルかつエレガントに書かれるべきである、という哲学を採用しています。
Yii は、何らかのデザインパターンを厳密に守ることを主たる目的として大袈裟な設計をすることは、決してしようとしません。
- Yii は、検証済みで直ちに使える多数の機能を提供するフル装備のフレームワークです:
リレーショナルデータベースと NoSQL データベースの両方のためのクエリビルダとアクティブレコード; RESTful API 開発サポート; 多層構成のキャッシュサポート; その他諸々。
- Yii は、検証済みで直ちに使える多数の機能を提供するフル装備のフレームワークです
リレーショナルデータベースと NoSQL データベースの両方のためのクエリビルダとアクティブレコード、RESTful API 開発サポート、多層構成のキャッシュサポート、その他諸々。
- Yii は極めて拡張性の高いフレームワークです。あなたはコアのコードのほとんど全ての要素をカスタマイズしたり置き換えたりすることが出来ます。
また、Yii の堅固なエクステンションアーキテクチャを利用して、再配布可能なエクステンションを使用したり開発したりすることも出来ます。
- 高性能であることは常に Yii の主たる目的の一つです。
また、Yii の堅固なエクステンションアーキテクチャを利用して、再配布可能なエクステンションを使用したり開発したりすることも出来ます。
- 高性能であることは常に Yii の主たる目です。
Yii は「独演会」ではありません。Yii は [強力なコア開発チーム][] および Yii 開発に間断なく貢献してくれるプロフェッショナルの大きなコミュニティーに支えられたプロジェクトです。
Yii はワンマンショーではありません。Yii は [強力なコア開発チーム][] および Yii 開発に間断なく貢献してくれるプロフェッショナルの大きなコミュニティーに支えられたプロジェクトです。
Yii 開発チームは最新のウェブ開発の潮流や、他のフレームワークやプロジェクトに見られる最善の慣行と機能から目を離しません。
他のところで見られる関連性の高い最善の慣行と機能は定期的にコアフレームワークに組み込まれ、シンプルかつエレガントなインターフェイスを通じて公開されます。
他のところで見出された関連性の高い最善の慣行と機能は、定期的にコアフレームワークに組み込まれ、シンプルかつエレガントなインターフェイスを通じて公開されます。
[強力なコア開発チーム]: http://www.yiiframework.com/about/
......@@ -40,7 +40,7 @@ Yii のバージョン
Yii は現在、利用可能な二つのメジャーバージョン、すなわち 1.1 と 2.0 を持っています。
バージョン 1.1 は古い世代のもので、現在はメンテナンスモードにあります。
バージョン 2.0 は、最新のテクノロジーとプロトコル、例えば、Composer、PSR、名前空間、トレイトなどを採用して、Yii を完全に書き直したものです。
バージョン 2.0 がこのフレームワークの現在の世代を表すものであり、今後数年間にわたって主要な開発努力の対象となるものです。
バージョン 2.0 がこのフレームワークの現世代を表すものであり、今後数年間にわたって主要な開発努力の対象となるものです。
このガイドは主としてバージョン 2.0 について述べます。
......@@ -48,9 +48,10 @@ Yii は現在、利用可能な二つのメジャーバージョン、すなわ
------------------
Yii 2.0 は PHP 5.4.0 以上を必要とします。
個別の機能に対するさらに詳細な必要条件は、全ての Yii リリースに含まれている必要条件チェッカーを走らせることによって知ることが出来ます。
個別の機能に対する詳細な必要条件は、全ての Yii リリースに含まれている必要条件チェッカを走らせることによって知ることが出来ます。
Yii は純粋なオブジェクト指向のフレームワークですので、Yii を使うためにはオブジェクト指向プログラミング (OOP) の基本的な知識が必要とされます。
Yii を使うためには、オブジェクト指向プログラミング (OOP) の基本的な知識が必要です。
なぜなら、Yii は純粋な OOP ベースのフレームワークだからです。
また、Yii 2.0 は [名前空間](http://php.net/manual/ja/language.namespaces.php)[トレイト](http://php.net/manual/ja/language.oop5.traits.php) のような PHP の最新の機能を利用しています。
これらの概念を理解することは、Yii 2.0 を採用することをより一層容易にするでしょう。
......@@ -2,16 +2,15 @@
==============
「はじめよう」の章全体を読み通したなら、いまやあなたは、完全な Yii のアプリケーションを作成したことがある、と言うことが出来ます。
その過程で、あなたは HTML フォームを通じてユーザからデータを取得することや、データベースからデータを取得すること、また、ページ付けをしてデータを表示することなど、
必要とされることが多いいくつかの機能を実装する方法を学びました。
その過程で、あなたは HTML フォームを通じてユーザからデータを取得することや、データベースからデータを取得すること、また、ページ付けをしてデータを表示することなど、必要とされることが多いいくつかの機能を実装する方法を学びました。
また、[Gii](tool-gii.md) を使ってコードを自動的に生成する方法も学びました。
Gii をコード生成に使うと、ウェブ開発のプロセスの大部分が、いくつかのフォームに入力していくだけの簡単な仕事になります。
この節では、Yii フレームワークを使うときの生産性を更に高めるために利用できるリソースについてまとめます。
* ドキュメント
- [公式ガイド](http://www.yiiframework.com/doc-2.0/guide-README.html):
Definitive(最も確実な) という名前が示すように、このガイドは Yii がどのように動作すべきものかを正確に記述し、
- [決定版ガイド](http://www.yiiframework.com/doc-2.0/guide-README.html):
Definitive(決定的な) という名前が示すように、このガイドは Yii がどのように動作すべきものかを正確に記述し、
Yii を使用するについての全般的な手引きを提供するものです。
これは唯一最重要な Yii のチュートリアルであり、Yii のコードを少しでも書く前に読むべきものです。
- [クラスリファレンス](http://www.yiiframework.com/doc-2.0/index.html):
......@@ -21,7 +20,7 @@ Gii をコード生成に使うと、ウェブ開発のプロセスの大部分
- [Wiki の記事](http://www.yiiframework.com/wiki/?tag=yii2):
Wiki の記事は、Yii のユーザが自身の経験に基づいて書いたものです。
ほとんどの記事は、料理本のレシピのように書かれており、特定の問題を Yii を使って解決する方法を示しています。
これらの記事の品質は公式ガイドほどには良くないかもしれませんが、
これらの記事の品質は決定版ガイドほどには良くないかもしれませんが、
より広範なトピックをカバーしていることと、たいていは即座に使えるソリューションを提供してくれることにおいて有用なものです。
- [書籍](http://www.yiiframework.com/doc/)
* [エクステンション](http://www.yiiframework.com/extensions/):
......
......@@ -3,20 +3,17 @@
Yii のインストールが終ると、実際に動く Yii のアプリケーションにアクセスすることが出来るようになります。
その URL は、`http://hostname/basic/web/index.php` あるいは `http://hostname/index.php` など、設定によって異なります。
この節では、アプリケーションに組み込み済みの機能を紹介し、コードがどのように組織されているか、
そして、一般にアプリケーションがリクエストをどのように処理するかを説明します。
この節では、アプリケーションに組み込み済みの機能を紹介し、コードがどのように組織されているか、そして、一般にアプリケーションがリクエストをどのように処理するかを説明します。
> Info|情報: 話を簡単にするために、この「始めよう」のチュートリアルを通じて、
`basic/web` をウェブサーバのドキュメントルートとして設定したと仮定します。そして、
アプリケーションにアクセスするための URL は `http://hostname/index.php` またはそれに似たものになるように
設定したと仮定します。
> Info|情報: 話を簡単にするために、この「始めよう」のチュートリアルを通じて、`basic/web` をウェブサーバのドキュメントルートとして設定したと仮定します。
そして、アプリケーションにアクセスするための URL は `http://hostname/index.php` またはそれに似たものになるように設定したと仮定します。
必要に応じて、説明の中の URL を読み替えてください。
機能<a name="functionality"></a>
----
インストールされた基本的なアプリケーションは4つのページを持っています:
インストールされた基本的なアプリケーションは四つのページを持っています。
* ホームページ: `http://hostname/index.php` の URL にアクセスすると表示されます。
* 「について」のページ。
......@@ -29,21 +26,21 @@ Yii のインストールが終ると、実際に動く Yii のアプリケー
ヘッダには、異なるページ間を行き来することを可能にするメインメニューバーがあります。
ブラウザのウィンドウの下部にツールバーがあることにも気がつくはずです。
これは Yii によって提供される便利な [デバッグツールバー](tool-debugger.md) であり、ログメッセージ、
レスポンスのステータス、データベースクエリの実行状況、その他、たくさんのデバッグ情報を記録・表示するものです。
これは Yii によって提供される便利な [デバッグツールバー](tool-debugger.md)
であり、ログメッセージ、レスポンスのステータス、データベースクエリの実行状況、その他、たくさんのデバッグ情報を記録・表示するものです。
アプリケーションの構造<a name="application-structure"></a>
----------------------
アプリケーションにとって最も重要なディレクトリとファイルは (アプリケーションのルートディレクトリが `basic` だと仮定すると) 以下の通りです:
アプリケーションにとって最も重要なディレクトリとファイルは (アプリケーションのルートディレクトリが `basic` だと仮定すると) 以下の通りです
```
basic/ アプリケーションのベースパス
composer.json Composer によって使用される。パッケージ情報を記述
config/ アプリケーションその他のコンフィギュレーションを格納
console.php コンソールアプリケーションのコンフィギュレーション
web.php ウェブアプリケーションのコンフィギュレーション
config/ アプリケーションその他の構成情報を格納
console.php コンソールアプリケーションの構成情報
web.php ウェブアプリケーションの構成情報
commands/ コンソールコマンドのクラスを格納
controllers/ コントローラのクラスを格納
models/ モデルのクラスを格納
......@@ -56,7 +53,7 @@ basic/ アプリケーションのベースパス
yii Yii コンソールコマンド実行スクリプト
```
一般に、アプリケーションのファイルは二種類に分けることが出来ます: `basic/web` の下にあるファイルとその他のディレクトリの下にあるファイルです。
一般に、アプリケーションのファイルは二種類に分けることが出来ます。すなわち、`basic/web` の下にあるファイルとその他のディレクトリの下にあるファイルです。
前者は HTTP で (すなわちブラウザで) 直接にアクセスすることが出来ますが、後者は直接のアクセスは出来ませんし、許可すべきでもありません。
Yii は [モデル・ビュー・コントローラ (MVC)](http://wikipedia.org/wiki/Model-view-controller) デザインパターンを実装していますが、それが上記のディレクトリ構成にも反映されています。
......@@ -81,7 +78,7 @@ Yii は [モデル・ビュー・コントローラ (MVC)](http://wikipedia.org/
![リクエストのライフサイクル](images/request-lifecycle.png)
1. ユーザが [エントリスクリプト](structure-entry-scripts.md) `web/index.php` に対してリクエストを出します。
2. エントリスクリプトはアプリケーションの [コンフィギュレーション](concept-configurations.md) を読み出して、
2. エントリスクリプトはアプリケーションの [構成情報](concept-configurations.md) を読み出して、
リクエストを処理する [アプリケーション](structure-applications.md) のインスタンスを作成します。
3. アプリケーションは、[リクエスト](runtime-requests.md) アプリケーションコンポーネントの助力を得て、
リクエストされた [ルート](runtime-routing.md) を解決します。
......
......@@ -192,7 +192,7 @@ Helpers
-------
* [Overview](helper-overview.md)
* **TBD** [ArrayHelper](helper-array.md)
* [ArrayHelper](helper-array.md)
* **TBD** [Html](helper-html.md)
* **TBD** [Url](helper-url.md)
* **TBD** [Security](helper-security.md)
......
ArrayHelper
===========
Additionally to [rich set of PHP array functions](http://php.net/manual/en/book.array.php) Yii array helper provides
extra static methods allowing you to deal with arrays more efficiently.
Getting values
--------------
### Getting a single value
Retrieving values from an array, an object or a complex structure consisting of both using standard PHP is quite
repetitive. You have to check if key exists with `isset` first, then if it does you're getting it, if not,
providing default value:
```php
class User
{
public $name = 'Alex';
}
$array = [
'foo' => [
'bar' => new User(),
]
];
$value = isset($array['foo']['bar']->name) ? $array['foo']['bar']->name : null;
```
Yii provides a very convenient method to do it:
```php
$value = ArrayHelper::getValue($array, 'foo.bar.name');
```
First method argument is where we're getting value from. Second argument specifies how to get the data. It could be one
of the following:
- Name of array key or object property to retieve value from.
- Set of dot separated array key or object property names. The one we've used in the example above.
- A callback returning a value.
The callback should be the following:
```php
$fullName = ArrayHelper::getValue($user, function ($user, $defaultValue) {
return $user->firstName . ' ' . $user->lastName;
});
```
Third optional argument is default value which is `null` if not specified. Could be used as follows:
```php
$username = ArrayHelper::getValue($comment, 'user.username', 'Unknown');
```
In case you want to get the value and then immediately remove it from array you can use `remove` method:
```php
$array = ['type' => 'A', 'options' => [1, 2]];
$type = ArrayHelper::remove($array, 'type');
```
After executing the code `$array` will contain `['options' => [1, 2]]` and `$type` will be `A`. Note that unlike
`getValue` method, `remove` supports simple key names only.
### Checking if key exists
`ArrayHelper::keyExists` works the same way as [array_key_exists](http://php.net/manual/en/function.array-key-exists.php)
except when trird argument is `false`. In this case it checks for a key in case insensitive manner:
```php
$data1 = [
'userName' => 'Alex',
];
$data2 = [
'username' => 'Carsten',
];
if (!ArrayHelper::keyExists('username', $data1, false) || !ArrayHelper::keyExists('username', $data2, false)) {
echo "Please provide username.";
}
```
### Getting a column
Often you need to get a column of values from array of data rows or objects. Common keys is getting a list of IDs.
```php
$data = [
['id' => '123', 'data' => 'abc'],
['id' => '345', 'data' => 'def'],
];
$ids = ArrayHelper::getColumn($array, 'id');
```
The result will be `['123', '345']`.
If additional transformations are required or the way of getting value is complex, second argument could be specified
as an anonymous function:
```php
$result = ArrayHelper::getColumn($array, function ($element) {
return $element['id'];
});
```
Index array by key specified
----------------------------
In order to indexes an array according to a specified key `index` method could be used. The input array should be
multidimensional or an array of objects. The key can be a key name of the sub-array, a property name of object, or
an anonymous function which returns the key value given an array element.
If a key value is null, the corresponding array element will be discarded and not put in the result. For example,
```php
$array = [
['id' => '123', 'data' => 'abc'],
['id' => '345', 'data' => 'def'],
];
$result = ArrayHelper::index($array, 'id');
// the result is:
// [
// '123' => ['id' => '123', 'data' => 'abc'],
// '345' => ['id' => '345', 'data' => 'def'],
// ]
// using anonymous function
$result = ArrayHelper::index($array, function ($element) {
return $element['id'];
});
```
Map array
---------
In order to build a map (key-value pairs) from a multidimensional array or an array of objects you can use `map` method.
The `$from` and `$to` parameters specify the key names or property names to set up the map. Optionally, one can further
group the map according to a grouping field `$group`. For example,
```php
$array = [
['id' => '123', 'name' => 'aaa', 'class' => 'x'],
['id' => '124', 'name' => 'bbb', 'class' => 'x'],
['id' => '345', 'name' => 'ccc', 'class' => 'y'],
);
$result = ArrayHelper::map($array, 'id', 'name');
// the result is:
// [
// '123' => 'aaa',
// '124' => 'bbb',
// '345' => 'ccc',
// ]
$result = ArrayHelper::map($array, 'id', 'name', 'class');
// the result is:
// [
// 'x' => [
// '123' => 'aaa',
// '124' => 'bbb',
// ],
// 'y' => [
// '345' => 'ccc',
// ],
// ]
```
Sort array
----------
`sort` method helps to sort an array of objects or nested arrays by one or several keys. For example,
```php
$data = [
['age' => 30, 'name' => 'Alexander'],
['age' => 30, 'name' => 'Brian'],
['age' => 19, 'name' => 'Barney'],
];
ArrayHelper::multisort($data, ['age', 'name'], [ArrayHelper::SORT_ASC, ArrayHelper::SORT_DESC]);
```
After sorting we'll get the following in `$data`:
```php
[
['age' => 19, 'name' => 'Barney'],
['age' => 30, 'name' => 'Brian'],
['age' => 30, 'name' => 'Alexander'],
];
```
Second argument that specifies keys to sort by could be a string if it's a single key, an array in case of multiple keys
or an anonymous function like the following one:
```php
ArrayHelper::multisort($data, function($item) {
return isset($item['age']) ? ['age', 'name'] : 'name';
});
```
Third argument is direction. In case of sorting by a single key it could be either `ArrayHelper::SORT_ASC` or
`ArrayHelper::SORT_DESC`. If sorting by multiple values you can sort each value differently by providing an array of
sort direction.
Last argument is PHP sort flag that could take the same values as the ones passed to
PHP [sort()](http://php.net/manual/en/function.sort.php).
Finding out the type of array
-----------------------------
It is handy to know whether array is indexed or an associative. Here's an example:
```php
// no keys specified
$indexed = ['Qiang', 'Paul'];
echo ArrayHelper::isIndexed($indexed);
// all keys are strings
$associative = ['framework' => 'Yii', 'version' => '2.0'];
echo ArrayHelper::isAssociative($associative);
```
HTML-encoding and HTML-decoding values
--------------------------------------
In order to encode or decode special characters in an array of strings into HTML entities you can use the following:
```php
$encoded = ArrayHelper::htmlEncode($data);
$decoded = ArrayHelper::htmlDecode($data);
```
Only values will be encoded by default. By passing second argument as `false` you can encode arrays keys as well.
Encoding will use application charset and could be changed via third argument.
Merging arrays
--------------
/**
* Merges two or more arrays into one recursively.
* If each array has an element with the same string key value, the latter
* will overwrite the former (different from array_merge_recursive).
* Recursive merging will be conducted if both arrays have an element of array
* type and are having the same key.
* For integer-keyed elements, the elements from the latter array will
* be appended to the former array.
* @param array $a array to be merged to
* @param array $b array to be merged from. You can specify additional
* arrays via third argument, fourth argument etc.
* @return array the merged array (the original arrays are not changed.)
*/
public static function merge($a, $b)
Getting array from object
-------------------------
Often you need to convert an object or an array of objects into array. The most common case is converting active record
models in order to serve data arrays via REST API or use it otherwise. The following code could be used to do it:
```php
$posts = Post::find()->limit(10)->all();
$data = ArrayHelper::toArray($post, [
'app\models\Post' => [
'id',
'title',
// the key name in array result => property name
'createTime' => 'created_at',
// the key name in array result => anonymous function
'length' => function ($post) {
return strlen($post->content);
},
],
]);
```
The first argument contains the data we want to convert. In our case we're converting a `Post` AR model.
The second argument is conversion mapping per class. We're setting a mapping for `Post` model.
Each mapping array contains a set of mappings. Each mapping could be:
- A field name to include as is.
- A key-value pair of desired array key name and model colum name to take value from.
- A key-value pair of desired array key name and a callback which return value will be used.
The result of conversion above will be:
```php
[
'id' => 123,
'title' => 'test',
'createTime' => '2013-01-01 12:00AM',
'length' => 301,
]
```
It is possible to provide default way of converting object to array for a specific class by implementing
[[yii\base\Arrayable|Arrayable]] interface in that class.
\ No newline at end of file
......@@ -25,7 +25,7 @@ Core Helper Classes
The following core helper classes are provided in the Yii releases:
- ArrayHelper
- [ArrayHelper](helper-array.md)
- Console
- FileHelper
- Html
......
......@@ -3,7 +3,7 @@ Uploading Files
> Note: This section is under development.
Uploading files in Yii is done via the form model, its validation rules and some controller code. Let's review what's needed
Uploading files in Yii is done via the a form model, its validation rules and some controller code. Let's review what's needed
to handle uploads properly.
Form model
......@@ -46,7 +46,7 @@ the HTML form. The attribute has the validation rule named `file` that uses [[yi
Form view
---------
Next create a view that will render the form.
Next, create a view that will render the form:
```php
<?php
......@@ -61,7 +61,7 @@ $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
<?php ActiveForm::end(); ?>
```
The `'enctype' => 'multipart/form-data'` is important since it allows file uploads. `fileInput()` represents a form
The `'enctype' => 'multipart/form-data'` is necessary because it allows file uploads. `fileInput()` represents a form
input field.
Controller
......@@ -96,10 +96,8 @@ class SiteController extends Controller
}
```
Instead of `model->load(...)` we are using `UploadedFile::getInstance(...)`. [[\yii\web\UploadedFile|UploadedFile]]
does not run the model validation. It only provides information about the uploaded file. Therefore, you need to run
validation manually via `$model->validate()`. This triggers the [[yii\validators\FileValidator|FileValidator]] that
expects a file:
Instead of `model->load(...)`, we are using `UploadedFile::getInstance(...)`. [[\yii\web\UploadedFile|UploadedFile]]
does not run the model validation, rather it only provides information about the uploaded file. Therefore, you need to run the validation manually via `$model->validate()` to trigger the [[yii\validators\FileValidator|FileValidator]] that expects a file:
```php
$file instanceof UploadedFile || $file->error == UPLOAD_ERR_NO_FILE //in the code framework
......@@ -144,7 +142,7 @@ public function rules()
}
```
Keep in mind that only the file extension will be validated, but not the actual file content. In order to validate content as well use the `mimeTypes` property of `FileValidator`:
Keep in mind that only the file extension will be validated, but not the actual file content. In order to validate the content as well, use the `mimeTypes` property of `FileValidator`:
```php
public function rules()
......@@ -164,7 +162,9 @@ received a valid image that can be then either saved or processed using the [Ima
### Uploading multiple files
If you need to download multiple files at once some adjustments are required. View:
If you need to download multiple files at once, some adjustments are required.
View:
```php
<?php
......@@ -241,5 +241,5 @@ class SiteController extends Controller
}
```
The difference is `UploadedFile::getInstances($model, 'file');` instead of `UploadedFile::getInstance($model, 'file');`.
The difference is using `UploadedFile::getInstances($model, 'file');` instead of `UploadedFile::getInstance($model, 'file');`.
The former returns instances for **all** uploaded files while the latter gives you only a single instance.
......@@ -140,7 +140,8 @@ Formatting Numbers <a name="numbers"></a>
For formatting numeric values the formatter class provides the following methods:
- [[yii\i18n\Formatter::asInteger()|integer]] - the value is formatted as an integer e.g. `42`.
- [[yii\i18n\Formatter::asDecimal()|decimal]] - the value is formatted as a decimal number considering decimal and thousand separators e.g. `42.123`.
- [[yii\i18n\Formatter::asDecimal()|decimal]] - the value is formatted as a decimal number considering decimal and thousand
separators e.g. `2,542.123` or `2.542,123`.
- [[yii\i18n\Formatter::asPercent()|percent]] - the value is formatted as a percent number e.g. `42%`.
- [[yii\i18n\Formatter::asScientific()|scientific]] - the value is formatted as a number in scientific format e.g. `4.2E4`.
- [[yii\i18n\Formatter::asCurrency()|currency]] - the value is formatted as a currency value e.g. `£420.00`.
......@@ -165,7 +166,7 @@ For example to adjust the maximum and minimum value of fraction digits you can c
Other formatters <a name="other"></a>
----------------
Additional to date, time and number formatting, Yii provides a set of other useful formatters for different purposes:
In addition to date, time and number formatting, Yii provides a set of other useful formatters for different situations:
- [[yii\i18n\Formatter::asRaw()|raw]] - the value is outputted as is, this is a pseudo-formatter that has no effect except that
`null` values will be formatted using [[nullDisplay]].
......@@ -181,13 +182,13 @@ Additional to date, time and number formatting, Yii provides a set of other usef
- [[yii\i18n\Formatter::asImage()|image]] - the value is formatted as an image tag.
- [[yii\i18n\Formatter::asUrl()|url]] - the value is formatted as a hyperlink.
- [[yii\i18n\Formatter::asBoolean()|boolean]] - the value is formatted as a boolean. By default `true` is rendered
as `Yes` and `false` as `No`, translated to the application language. You can adjust this by configuring
as `Yes` and `false` as `No`, translated to the current application language. You can adjust this by configuring
the [[yii\i18n\Formatter::booleanFormat]] property.
`null`-values <a name="null-values"></a>
-------------
For values that are `null` in PHP, the formatter class will print a placeholder instead of empty string which
For values that are `null` in PHP, the formatter class will print a placeholder instead of an empty string which
defaults to `(not set)` translated to the current application language. You can configure the
[[yii\i18n\Formatter::nullDisplay|nullDisplay]] property to set a custom placeholder.
If you want no special handling for `null` values, you can set [[yii\i18n\Formatter::nullDisplay|nullDisplay]] to `null`.
If you do not you want special handling for `null` values, you can set [[yii\i18n\Formatter::nullDisplay|nullDisplay]] to `null`.
......@@ -4,17 +4,17 @@ Theming
> Note: This section is under development.
A theme is a directory of view and layout files. Each file of the theme overrides corresponding file of an application
when rendered. A single application may use multiple themes and each may provide totally different experience. At any
when rendered. A single application may use multiple themes and each may provide totally different experiences. At any
time only one theme can be active.
> Note: Themes usually do not meant to be redistributed since views are too application specific. If you want to
redistribute customized look and feel consider CSS and JavaScript files in form of [asset bundles](structure-assets.md) instead.
> Note: Themes are usually not meant to be redistributed since views are too application specific. If you want to
redistribute a customized look and feel, consider CSS and JavaScript files in the form of [asset bundles](structure-assets.md) instead.
Configuring a theme
-------------------
Theme configuration is specified via `view` component of the application. In order to set up a theme to work with basic
application views the following should be in your application config file:
Theme configuration is specified via the `view` component of the application. In order to set up a theme to work with basic
application views, the following should be in your application config file:
```php
'components' => [
......@@ -27,8 +27,8 @@ application views the following should be in your application config file:
],
```
In the above `pathMap` defines a map of original paths to themed paths while `baseUrl` defines base URL for
resources referenced from theme files.
In the above, `pathMap` defines a map of original paths to themed paths while `baseUrl` defines the base URL for
resources referenced by theme files.
In our case `pathMap` is `['@app/views' => '@app/themes/basic']`. That means that every view in `@app/views` will be
first searched under `@app/themes/basic` and if a view exists in the theme directory it will be used instead of the
......@@ -40,7 +40,7 @@ For example, with a configuration above a themed version of a view file `@app/vi
### Theming modules
In order to theme modules `pathMap` may look like the following:
In order to theme modules, `pathMap` may look like the following:
```php
'components' => [
......@@ -59,8 +59,8 @@ It will allow you to theme `@app/modules/blog/views/comment/index.php` with `@ap
### Theming widgets
In order to theme a widget view located at `@app/widgets/currency/views/index.php` you need the following config for
view component theme:
In order to theme a widget view located at `@app/widgets/currency/views/index.php`, you need the following configuration for
the view component theme:
```php
'components' => [
......@@ -72,7 +72,7 @@ view component theme:
],
```
With the config above you can create themed version of `@app/widgets/currency/index.php` view in
With the configuration above you can create a themed version of the `@app/widgets/currency/index.php` view in
`@app/themes/basic/widgets/currency/index.php`.
Using multiple paths
......@@ -89,7 +89,7 @@ It is possible to map a single path to multiple theme paths. For example,
]
```
In this case, the view will be searched in `@app/themes/christmas/site/index.php` then if it's not found it will check
`@app/themes/basic/site/index.php`. If there's no view there as well application view will be used.
In this case, first the view will be searched for in `@app/themes/christmas/site/index.php` then if it's not found it will check
`@app/themes/basic/site/index.php`. If there's no view there as well, then the application view will be used.
This ability is especially useful if you want to temporary or conditionally override some views.
This ability is especially useful if you want to temporarily or conditionally override some views.
......@@ -83,4 +83,4 @@ public function beforeSave($insert)
}
```
The `validateAuthKey` method just needs to compare the `$authKey` variable, passed as parameter (itself retrieved from a cookie), with the value fetched from database.
The `validateAuthKey` method just needs to compare the `$authKey` variable, passed as a parameter (itself retrieved from a cookie), with the value fetched from the database.
Design Decisions
================
This document lists the design decisions that we have made after extensive discussions. Unless there are very strong
reasons, these decisions should be kept for consistency. Any change to these decisions should get agreement among
the core developers.
1. **[When to support path aliases](https://github.com/yiisoft/yii2/pull/3079#issuecomment-40312268)**
we should support path alias for properties that are configurable because using path aliases in configurations
are very convenient. In other cases, we should restrict the support for path aliases.
2. **When to translate messages**
messages should be translated when these are displayed to non-tech end user and make sense to him. HTTP status messages,
exceptions about the code etc. should not be translated. Console messages are always in English because of encoding
and codepage handling difficulties.
......@@ -207,6 +207,7 @@ Yii Framework 2 Change Log
- Bug #5049: `ActiveForm::validationDelay` should be applied to user types only (qiangxue)
- Bug #5055: Fixed `yii\console\controllers\CacheController` does not check if cache component instance of 'yii\caching\Cache' (klimov-paul)
- Bug #5126: Fixed text body and charset not being set for multipart mail (nkovacs)
- Bug #6305: `yii\i18n\Formatter::asParagraphs()` was not unicode-aware (samdark)
- Bug: Fixed inconsistent return of `\yii\console\Application::runAction()` (samdark)
- Bug: URL encoding for the route parameter added to `\yii\web\UrlManager` (klimov-paul)
- Bug: Fixed the bug that requesting protected or private action methods would cause 500 error instead of 404 (qiangxue)
......@@ -247,7 +248,6 @@ Yii Framework 2 Change Log
- Enh #3283: Added `$checkAjax` to `yii\web\User::loginRequired()` (qiangxue)
- Enh #3284: Added support for checking multiple ETags by `yii\filters\HttpCache` (qiangxue)
- Enh #3298: Supported configuring `View::theme` using a class name (netyum, qiangxue)
- Enh #3305: Added `refreshSchema()` method to `yii\console\controllers\BaseMigrateController` to allow flushing DB schema cache (6pblcb, samdark)
- Enh #3328: `BaseMailer` generates better text body from html body (armab)
- Enh #3380: Allow `value` in `defaultValueValidator` to be a closure (Alex-Code)
- Enh #3384: Added callback-style transactions (leandrogehlen, Ragazzo, samdark)
......
......@@ -624,15 +624,6 @@ abstract class BaseMigrateController extends Controller
return $migrations;
}
/**
* Flushes DB schema cache.
* This method should be implemented if connection has DB schema support.
* @since 2.0.1
*/
protected function refreshSchema()
{
}
/**
* Returns the migration history.
......
......@@ -179,14 +179,4 @@ class MigrateController extends BaseMigrateController
'version' => $version,
])->execute();
}
/**
* @inheritdoc
* @since 2.0.1
*/
protected function refreshSchema()
{
$this->db->schema->refresh();
$this->stdout("DB schema cache was flushed.\n", Console::FG_GREEN);
}
}
......@@ -322,7 +322,7 @@ class Formatter extends Component
if ($value === null) {
return $this->nullDisplay;
}
return str_replace('<p></p>', '', '<p>' . preg_replace('/\R{2,}/', "</p>\n<p>", Html::encode($value)) . '</p>');
return str_replace('<p></p>', '', '<p>' . preg_replace('/\R{2,}/u', "</p>\n<p>", Html::encode($value)) . '</p>');
}
/**
......
......@@ -52,6 +52,17 @@ return [
'Update' => 'بروزرسانی',
'View' => 'نما',
'Yes' => 'بله',
'in {delta, plural, =1{a year} other{# years}}' => '{delta} سال دیگر',
'in {delta, plural, =1{a month} other{# months}}' => '{delta} ماه دیگر',
'in {delta, plural, =1{a day} other{# days}}' => '{delta} روز دیگر',
'in {delta, plural, =1{an hour} other{# hours}}' => '{delta} ساعت دیگر',
'in {delta, plural, =1{a minute} other{# minutes}}' => '{delta} دقیقه دیگر',
'{delta, plural, =1{a month} other{# months}} ago' => '{delta} ماه قبل',
'{delta, plural, =1{a day} other{# days}} ago' => '{delta} روز قبل',
'{delta, plural, =1{an hour} other{# hours}} ago' => '{delta} ساعت قبل',
'{delta, plural, =1{a minute} other{# minutes}} ago' => '{delta} دقیقه قبل',
'{delta, plural, =1{a second} other{# seconds}} ago' => '{delta} ثانیه قبل',
'just now' => 'هم اکنون',
'You are not allowed to perform this action.' => 'شما دسترسی به انجام این عملیات را ندارید.',
'You can upload at most {limit, number} {limit, plural, one{file} other{files}}.' => 'شما حداکثر {limit, number} فایل را می‌توانید آپلود کنید.',
'the input value' => 'مقدار ورودی',
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment