Alexander Makarov
7 years ago
204 changed files with 5693 additions and 722 deletions
@ -0,0 +1,6 @@
|
||||
{ |
||||
"Warning:": "Perhatian:", |
||||
"Note:": "Catatan:", |
||||
"Info:": "Info:", |
||||
"Tip:": "Tips:" |
||||
} |
@ -0,0 +1,263 @@
|
||||
Bekerja dengan Database |
||||
====================== |
||||
|
||||
Bagian ini akan memaparkan bagaimana membuat halaman yang menampilkan daftar data negara yang diambil dari |
||||
tabel `country` pada database. Untuk menyelesaikan tugas ini, anda akan melakukan konfigurasi koneksi ke database, |
||||
membuat class [Active Record](db-active-record.md), membuat [action](structure-controllers.md), |
||||
dan membuat [view](structure-views.md). |
||||
|
||||
Sepanjang tutorial ini, anda akan mempelajari bagaimana cara untuk: |
||||
|
||||
* konfigurasi koneksi ke database, |
||||
* membuat class _ActiveRecord_, |
||||
* mengambil _(query)_ data menggunakan class _ActiveRecord_, |
||||
* menampilkan data ke view dengan halaman per halaman. |
||||
|
||||
Sebagai catatan untuk menyelesaikan bagian ini, anda harus memiliki pengetahuan dan pengalaman dasar dalam menggunakan database. |
||||
Secara khusus, anda harus mengetahui cara membuat database, dan cara menjalankan perintah SQL menggunakan aplikasi klien database. |
||||
|
||||
|
||||
Menyiapkan Database <span id="preparing-database"></span> |
||||
---------------------- |
||||
|
||||
Untuk memulai, buatlah database dengan nama `yii2basic`, yang akan digunakan untuk mengambil data dalam aplikasi anda. |
||||
Anda bisa membuat database SQLite, MySQL, PostgreSQL, MSSQL, atau Oracle, dimana Yii mendukung banyak aplikasi database. Untuk memudahkan, database yang digunakan adalah MySQL. |
||||
|
||||
Selanjutnya, buat tabel dengan nama `country` pada database, dan _insert_ beberapa data sampel. Anda bisa menjalankan perintah SQL dibawah untuk memudahkan: |
||||
|
||||
```sql |
||||
CREATE TABLE `country` ( |
||||
`code` CHAR(2) NOT NULL PRIMARY KEY, |
||||
`name` CHAR(52) NOT NULL, |
||||
`population` INT(11) NOT NULL DEFAULT '0' |
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8; |
||||
|
||||
INSERT INTO `country` VALUES ('AU','Australia',24016400); |
||||
INSERT INTO `country` VALUES ('BR','Brazil',205722000); |
||||
INSERT INTO `country` VALUES ('CA','Canada',35985751); |
||||
INSERT INTO `country` VALUES ('CN','China',1375210000); |
||||
INSERT INTO `country` VALUES ('DE','Germany',81459000); |
||||
INSERT INTO `country` VALUES ('FR','France',64513242); |
||||
INSERT INTO `country` VALUES ('GB','United Kingdom',65097000); |
||||
INSERT INTO `country` VALUES ('IN','India',1285400000); |
||||
INSERT INTO `country` VALUES ('RU','Russia',146519759); |
||||
INSERT INTO `country` VALUES ('US','United States',322976000); |
||||
``` |
||||
|
||||
Hingga saat ini, anda memiliki database bernama `yii2basic`, dan didalamnya terdapat tabel `country` dengan tiga kolom, berisi 10 baris data. |
||||
|
||||
Konfigurasi Koneksi Database <span id="configuring-db-connection"></span> |
||||
--------------------------- |
||||
|
||||
Sebelum melanjutkan, pastikan anda memasang ekstensi PHP [PDO](http://www.php.net/manual/en/book.pdo.php) dan |
||||
driver PDO untuk database yang anda gunakan (misal, `pdo_mysql` untuk MySQL). Ini adalah kebutuhan mendasar |
||||
jika aplikasi anda menggunakan _relational database_. |
||||
|
||||
Jika sudah terpasang, buka file `config/db.php` dan sesuaikan parameter yang sesuai untuk database anda. Secara default, |
||||
isi file konfigurasi tersebut adalah: |
||||
|
||||
```php |
||||
<?php |
||||
|
||||
return [ |
||||
'class' => 'yii\db\Connection', |
||||
'dsn' => 'mysql:host=localhost;dbname=yii2basic', |
||||
'username' => 'root', |
||||
'password' => '', |
||||
'charset' => 'utf8', |
||||
]; |
||||
``` |
||||
|
||||
File `config/db.php` adalah tipikal [konfigurasi](concept-configurations.md) yang menggunakan file. File konfigurasi seperti ini menentukan parameter-parameter |
||||
yang dibutuhkan untuk membuat dan menginisialisasi objek [[yii\db\Connection]], dimana anda dapat menjalankan perintah SQL |
||||
dengan database yang dituju. |
||||
|
||||
Konfigurasi koneksi database di atas dapat diakses pada kode aplikasi melalui _expression_ `Yii::$app->db`. |
||||
|
||||
> Info: File `config/db.php` akan di _include_ oleh konfigurasi aplikasi utama `config/web.php`, |
||||
yang berfungsi sebagai konfigurasi untuk inisialisasi objek [aplikasi](structure-applications.md). |
||||
Untuk penjelasan lebih lengkap, silahkan lihat bagian [Konfigurasi](concept-configurations.md). |
||||
|
||||
Jika anda membutuhkan dukungan database yang tidak didukung oleh Yii, silahkan cek _extensions_ di bawah ini: |
||||
|
||||
- [Informix](https://github.com/edgardmessias/yii2-informix) |
||||
- [IBM DB2](https://github.com/edgardmessias/yii2-ibm-db2) |
||||
- [Firebird](https://github.com/edgardmessias/yii2-firebird) |
||||
|
||||
|
||||
Membuat Active Record <span id="creating-active-record"></span> |
||||
------------------------- |
||||
|
||||
Untuk mengambil data di tabel `country`, buat class turunan [Active Record](db-active-record.md) |
||||
dengan nama `Country`, dan simpan pada file `models/Country.php`. |
||||
|
||||
```php |
||||
<?php |
||||
|
||||
namespace app\models; |
||||
|
||||
use yii\db\ActiveRecord; |
||||
|
||||
class Country extends ActiveRecord |
||||
{ |
||||
} |
||||
``` |
||||
|
||||
_Class_ `Country` di _extends_ dari [[yii\db\ActiveRecord]]. Anda tidak perlu untuk menulis kode di dalamnya! Hanya dengan kode di atas, |
||||
Yii akan mengetahui nama tabel yang dimaksud dari nama _class_ tersebut. |
||||
|
||||
> Info: Jika nama _class_ tidak sesuai dengan nama tabel, anda dapat meng-_override_ |
||||
method [[yii\db\ActiveRecord::tableName()]] untuk menentukan nama tabel secara eksplisit. |
||||
|
||||
Menggunakan class `Country`, anda bisa memanipulasi data pada tabel `country` dengan mudah, sebagaimana yang ditunjukkan pada kode di bawah ini: |
||||
|
||||
```php |
||||
use app\models\Country; |
||||
|
||||
// mengambil semua negara dari tabel country, dan mengurutkan berdasarkan "name" (nama) |
||||
$countries = Country::find()->orderBy('name')->all(); |
||||
|
||||
// mengambil negara yang memiliki primary key "US" |
||||
$country = Country::findOne('US'); |
||||
|
||||
// menampilkan "United States" |
||||
echo $country->name; |
||||
|
||||
// Mengganti nama negara menjadi "U.S.A." dan menyimpan ke database |
||||
$country->name = 'U.S.A.'; |
||||
$country->save(); |
||||
``` |
||||
|
||||
> Info: _Active Record_ adalah cara yang efektif untuk mengakses dan memanipulasi data dari database secara _object-oriented_. |
||||
Anda bisa mengetahui lebih banyak lagi pada bagian [Active Record](db-active-record.md). Sebagai alternatif, anda mungkin berinteraksi dengan database menggunakan metode data akses yang lebih mendasar yang disebut [Data Access Objects](db-dao.md). |
||||
|
||||
|
||||
Membuat Action <span id="creating-action"></span> |
||||
------------------ |
||||
|
||||
Untuk menampilkan data negara ke pengguna, anda harus membuat _action_. Dibanding menempatkan _action_ baru ini pada _controller_ `site` |
||||
seperti yang sudah anda lakukan pada bagian sebelumnya, sekarang ini ada baiknya membuat spesifik _controller_ |
||||
untuk semua _action_ yang berhubungan dengan data negara. Namakan _controller_ baru ini dengan `CountryController`, dan buat |
||||
_action_ `index` pada controller tersebut, seperti yang ditunjukkan di bawah ini. |
||||
|
||||
```php |
||||
<?php |
||||
|
||||
namespace app\controllers; |
||||
|
||||
use yii\web\Controller; |
||||
use yii\data\Pagination; |
||||
use app\models\Country; |
||||
|
||||
class CountryController extends Controller |
||||
{ |
||||
public function actionIndex() |
||||
{ |
||||
$query = Country::find(); |
||||
|
||||
$pagination = new Pagination([ |
||||
'defaultPageSize' => 5, |
||||
'totalCount' => $query->count(), |
||||
]); |
||||
|
||||
$countries = $query->orderBy('name') |
||||
->offset($pagination->offset) |
||||
->limit($pagination->limit) |
||||
->all(); |
||||
|
||||
return $this->render('index', [ |
||||
'countries' => $countries, |
||||
'pagination' => $pagination, |
||||
]); |
||||
} |
||||
} |
||||
``` |
||||
|
||||
Simpan kode di atas pada file `controllers/CountryController.php`. |
||||
|
||||
_Action_ `index` memanggil `Country::find()`. _Method_ _Active Record_ ini membuat _query_ ke database dan mengambil semua data negara dari tabel `country`. |
||||
Untuk membatasi jumlah negara yang didapatkan pada setiap pengambilan data, _query_ tersebut dipecah menjadi halaman per halaman dengan bantuan dari |
||||
objek [[yii\data\Pagination]]. Objek `Pagination` diperuntukkan untuk dua tujuan: |
||||
|
||||
* Menentukan klausa `offset` dan `limit` pada perintah SQL yang digunakan untuk _query_ agar mengambil |
||||
hanya satu halaman data dalam sekali perintah (pada umumnya akan mengambil 5 baris dalam satu halaman). |
||||
* Digunakan pada _view_ untuk menampilkan tombol halaman yang terdiri dari tombol-tombol nomor halaman, yang selanjutnya akan dijelaskan |
||||
pada sub bagian berikutnya. |
||||
|
||||
Di akhir kode, _action_ `index` me-_render_ _view_ dengan nama `index`, dan mengirimkan data negara beserta dengan informasi |
||||
halaman dari data tersebut. |
||||
|
||||
|
||||
Membuat View <span id="creating-view"></span> |
||||
--------------- |
||||
|
||||
Di dalam folder `views`, pertama-tama buatlah sub-folder dengan nama `country`. Folder ini akan digunakan untuk menyimpan semua |
||||
_view_ yang akan di _render_ oleh _controller_ `country`. Di dalam folder `views/country`, buatlah file dengan nama `index.php` |
||||
berisi kode di bawah ini: |
||||
|
||||
```php |
||||
<?php |
||||
use yii\helpers\Html; |
||||
use yii\widgets\LinkPager; |
||||
?> |
||||
<h1>Countries</h1> |
||||
<ul> |
||||
<?php foreach ($countries as $country): ?> |
||||
<li> |
||||
<?= Html::encode("{$country->name} ({$country->code})") ?>: |
||||
<?= $country->population ?> |
||||
</li> |
||||
<?php endforeach; ?> |
||||
</ul> |
||||
|
||||
<?= LinkPager::widget(['pagination' => $pagination]) ?> |
||||
``` |
||||
|
||||
Terkait dengan tampilan data negara, _view_ ini terdiri dari dua bagian. Bagian pertama, dilakukan perulangan _(looping)_ pada data negara yang tersedia dan di-_render_ sebagai _unordered list_ HTML. |
||||
Bagian kedua, _widget_ [[yii\widgets\LinkPager]] di-_render_ menggunakan informasi halaman _(pagination)_ yang dikirimkan dari _action_. |
||||
_Widget_ `LinkPager` menampilkan tombol-tombol halaman. Mengklik pada salah satu tombol tersebut akan melakukan pengambilan data negara |
||||
terkait dengan halaman yang diklik. |
||||
|
||||
|
||||
Mari Kita Coba <span id="trying-it-out"></span> |
||||
------------- |
||||
|
||||
Untuk melihat bagaimana kode-kode di atas bekerja, gunakan browser anda untuk mengakses URL ini: |
||||
|
||||
``` |
||||
http://hostname/index.php?r=country%2Findex |
||||
``` |
||||
|
||||
![Daftar Country](images/start-country-list.png) |
||||
|
||||
Awalnya, anda akan melihat sebuah halaman yang menampilkan 5 negara. Dibawah daftar negara tersebut, anda akan melihat tombol halaman yang berjumlah empat tombol. |
||||
Jika anda mengklik tombol "2", anda akan melihat halaman tersebut menampilkan 5 negara lain pada database: halaman kedua pada record. |
||||
Silahkan melakukan observasi secara perlahan-lahan dan anda akan mengetahui bahwa URL pada browser juga akan berganti menjadi |
||||
|
||||
``` |
||||
http://hostname/index.php?r=country%2Findex&page=2 |
||||
``` |
||||
|
||||
Di belakang layar, [[yii\data\Pagination|Pagination]] menyediakan semua kebutuhkan untuk memecah data menjadi halaman per halaman: |
||||
|
||||
* Pertama-tama, [[yii\data\Pagination|Pagination]] menampilkan halaman pertama, dimana menjalankan perintah SELECT pada tabel `country` |
||||
dengan klausa `LIMIT 5 OFFSET 0`. Hasilnya, 5 negara pertama akan diambil dan ditampilkan. |
||||
* _Widget_ [[yii\widgets\LinkPager|LinkPager]] me-_render_ tombol halaman menggunakan URL |
||||
yang dibentuk oleh method [[yii\data\Pagination::createUrl()|Pagination]]. URL tersebut mengandung _query string_ `page`, yang |
||||
merupakan representasi dari nomor halaman. |
||||
* Jika anda mengklik tombol halaman "2", sebuah _request_ yang mengarah ke _route_ `country/index` akan dijalankan hingga selesai. |
||||
[[yii\data\Pagination|Pagination]] membaca _query string_ `page` dari URL dan kemudian menentukan halaman sekarang adalah halaman 2. |
||||
Query data negara yang baru mengandung klausa `LIMIT 5 OFFSET 5` dan mengambil 5 data negara selanjutnya untuk |
||||
kemudian ditampilkan. |
||||
|
||||
|
||||
Rangkuman <span id="summary"></span> |
||||
------- |
||||
|
||||
Pada bagian ini, anda mempelajari bagaimana bekerja dengan database. Anda juga mempelajari bagaimana cara mengambil dan membagi |
||||
data dengan halaman per halaman dengan bantuan [[yii\data\Pagination]] dan [[yii\widgets\LinkPager]]. |
||||
|
||||
Di bagian selanjutnya, anda akan mempelajari bagaimana menggunakan _generator_ kode yang disebut [Gii](https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md), |
||||
untuk membantu anda mengimplementasikan fitur-fitur umum pada aplikasi secara instan, seperti operasi _Create_-_Read_-_Update_-_Delete_ (CRUD) |
||||
untuk bekerja dengan data yang terdapat pada tabel di sebuah database. Sebenarnya, kode-kode yang barusan anda tulis, semuanya bisa |
||||
di _generate_ secara otomatis oleh Yii menggunakan tool Gii. |
@ -0,0 +1,245 @@
|
||||
Bekerja dengan Form |
||||
================== |
||||
|
||||
Bagian ini memaparkan bagaimana membuat halaman dengan form untuk mengambil data dari pengguna. |
||||
Halaman akan menampilkan form dengan input field Nama dan Email. |
||||
Setelah mendapatkan dua data dari pengguna, halaman akan menampilkan kembali data yang diinput pada form sebagai konfirmasi. |
||||
|
||||
Untuk mencapai tujuan, disamping membuat sebuah [_action_](structure-controllers.md), dan |
||||
dua [_view_](structure-views.md), anda juga harus membuat [_model_](structure-models.md). |
||||
|
||||
Sepanjang tutorial ini, anda akan mempelajari bagaimana cara untuk: |
||||
|
||||
* Membuat sebuah [model](structure-models.md) sebagai representasi data yang diinput oleh pengguna melalui form, |
||||
* Membuat _rules_ untuk memvalidasi data yang telah diinput. |
||||
* Membuat form HTML di dalam [view](structure-views.md). |
||||
|
||||
Membuat Model <span id="creating-model"></span> |
||||
---------------- |
||||
|
||||
Data yang akan diambil dari pengguna akan direpresentasikan oleh class model `EntryForm` sebagaimana ditunjukkan di bawah dan |
||||
di simpan pada file `models/EntryForm.php`. Silahkan membaca bagian [Class Autoloading](concept-autoloading.md) |
||||
untuk penjelasan lengkap mengenai penamaan file class. |
||||
|
||||
```php |
||||
<?php |
||||
|
||||
namespace app\models; |
||||
|
||||
use Yii; |
||||
use yii\base\Model; |
||||
|
||||
class EntryForm extends Model |
||||
{ |
||||
public $name; |
||||
public $email; |
||||
|
||||
public function rules() |
||||
{ |
||||
return [ |
||||
[['name', 'email'], 'required'], |
||||
['email', 'email'], |
||||
]; |
||||
} |
||||
} |
||||
``` |
||||
|
||||
Class di _extends_ dari [[yii\base\Model]], class standar yang disediakan oleh Yii, yang secara umum digunakan |
||||
untuk representasi data dari form. |
||||
|
||||
> Info: [[yii\base\Model]] digunakan sebagai _parent_ untuk class model yang tidak berhubungan dengan database. |
||||
[[yii\db\ActiveRecord]] normalnya digunakan sebagai _parent_ untuk class model yang berhubungan dengan tabel di database. |
||||
|
||||
Class `EntryForm` terdiri dari dua _public property_, `name` dan `email`, dimana akan digunakan untuk menyimpan |
||||
data yang diinput oleh pengguna. Class ini juga terdapat _method_ yang dinamakan `rules()`, yang akan mengembalikan (_return_) sejumlah |
||||
pengaturan (_rules_) untuk memvalidasi data. Pengaturan validasi (_Validation Rules_) yang di deklarasikan harus mendeskripsikan bahwa |
||||
|
||||
* kedua field, yaitu `name` and `email` wajib di input |
||||
* data `email` harus merupakan alamat email yang valid |
||||
|
||||
Jika anda memiliki objek `EntryForm` yang sudah mengandung data yang di input oleh pengguna, anda boleh memanggil |
||||
method [[yii\base\Model::validate()|validate()]] untuk melaksanakan validasi data. Kegagalan validasi data |
||||
akan menentukan (_set_) property [[yii\base\Model::hasErrors|hasErrors]] menjadi `true`, dan anda dapat mengetahui pesan kegagalan validasi |
||||
melalui [[yii\base\Model::getErrors|errors]]. |
||||
|
||||
```php |
||||
<?php |
||||
$model = new EntryForm(); |
||||
$model->name = 'Qiang'; |
||||
$model->email = 'bad'; |
||||
if ($model->validate()) { |
||||
// Valid! |
||||
} else { |
||||
// Tidak Valid! |
||||
// Panggil $model->getErrors() |
||||
} |
||||
``` |
||||
|
||||
|
||||
Membuat Action <span id="creating-action"></span> |
||||
------------------ |
||||
|
||||
Selanjutnya, anda harus membuat `entry` _action_ pada controller `site` yang akan memanfaatkan model yang baru saja dibuat. Proses |
||||
membuat dan menggunakan _action_ dijelaskan pada bagian [Mengatakan Hello](start-hello.md). |
||||
|
||||
```php |
||||
<?php |
||||
|
||||
namespace app\controllers; |
||||
|
||||
use Yii; |
||||
use yii\web\Controller; |
||||
use app\models\EntryForm; |
||||
|
||||
class SiteController extends Controller |
||||
{ |
||||
// ...kode lain... |
||||
|
||||
public function actionEntry() |
||||
{ |
||||
$model = new EntryForm(); |
||||
|
||||
if ($model->load(Yii::$app->request->post()) && $model->validate()) { |
||||
// data yang valid diperoleh pada $model |
||||
|
||||
// lakukan sesuatu terhadap $model di sini ... |
||||
|
||||
return $this->render('entry-confirm', ['model' => $model]); |
||||
} else { |
||||
// menampilkan form pada halaman, ada atau tidaknya kegagalan validasi tidak masalah |
||||
return $this->render('entry', ['model' => $model]); |
||||
} |
||||
} |
||||
} |
||||
``` |
||||
|
||||
Pertama-tama, _action_ membuat objek `EntryForm`. Kemudian objek tersebut membangun model |
||||
menggunakan data dari `$_POST`, yang disediakan oleh Yii dengan method [[yii\web\Request::post()]]. |
||||
Jika model berhasil dibuat (misal, jika pengguna telah mengirim form HTML), _action_ akan memanggil method |
||||
[[yii\base\Model::validate()|validate()]] untuk memastikan data yang di input tersebut valid. |
||||
|
||||
> Info : _Expression_ `Yii::$app` adalah representasi dari objek [aplikasi](structure-applications.md), |
||||
dimana objek tersebut adalah _singleton_ yang bebas diakses secara global. Objek tersebut juga merupakan [service locator](concept-service-locator.md) yang |
||||
menyediakan _components_ seperti `request`, `response`, `db`, dll. untuk mendukung pekerjaan yang spesifik. |
||||
Pada kode di atas, _component_ `request` dari objek aplikasi digunakan untuk mengakses data `$_POST`. |
||||
|
||||
Jika tidak ada error, _action_ akan me-_render_ _view_ bernama `entry-confirm` untuk menginformasikan ke pengguna bahwa pengiriman |
||||
data tersebut berhasil. Jika tidak ada data yang dikirim atau data tersebut tidak valid, _view_ `entry` yang akan di _render_, |
||||
dimana form HTML akan ditampilkan, beserta informasi kegagalan pengiriman form tersebut. |
||||
|
||||
> Note: Pada contoh sederhana ini kita hanya me-_render_ halaman konfirmasi jika data yang dikirim tersebut valid. Pada prakteknya, |
||||
anda harus pertimbangkan untuk menggunakan [[yii\web\Controller::refresh()|refresh()]] atau [[yii\web\Controller::redirect()|redirect()]] |
||||
untuk mencegah [permasalahan pengiriman form](http://en.wikipedia.org/wiki/Post/Redirect/Get). |
||||
|
||||
|
||||
Membuat View <span id="creating-views"></span> |
||||
-------------- |
||||
|
||||
Terakhir, buatlah dua file _view_ dengan nama `entry-confirm` dan `entry`. _View_ ini akan di-_render_ oleh _action_ `entry`, |
||||
yang sebelumnya dibahas. |
||||
|
||||
_View_ `entry-confirm` hanya menampilkan data nama dan email. File _view_ tersebut harus di simpan di `views/site/entry-confirm.php`. |
||||
|
||||
```php |
||||
<?php |
||||
use yii\helpers\Html; |
||||
?> |
||||
<p>You have entered the following information:</p> |
||||
|
||||
<ul> |
||||
<li><label>Name</label>: <?= Html::encode($model->name) ?></li> |
||||
<li><label>Email</label>: <?= Html::encode($model->email) ?></li> |
||||
</ul> |
||||
``` |
||||
|
||||
_View_ `entry` akan menampilkan form HTML. File _view_ tersebut harus di simpan di `views/site/entry.php`. |
||||
|
||||
```php |
||||
<?php |
||||
use yii\helpers\Html; |
||||
use yii\widgets\ActiveForm; |
||||
?> |
||||
<?php $form = ActiveForm::begin(); ?> |
||||
|
||||
<?= $form->field($model, 'name') ?> |
||||
|
||||
<?= $form->field($model, 'email') ?> |
||||
|
||||
<div class="form-group"> |
||||
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?> |
||||
</div> |
||||
|
||||
<?php ActiveForm::end(); ?> |
||||
``` |
||||
|
||||
_View_ ini menggunakan [_widget_](structure-widgets.md) yaitu [[yii\widgets\ActiveForm|ActiveForm]] untuk |
||||
membangun form HTML. _Method_ `begin()` dan `end()` dari _widget_ masing-masing berfungsi untuk me-_render_ tag pembuka dan penutup |
||||
dari form tag. Diantara dua method tersebut, akan dibuat field input oleh |
||||
method [[yii\widgets\ActiveForm::field()|field()]]. Input field yang pertama diperuntukkan untuk data "name", |
||||
dan yang kedua diperuntukkan untuk data "email". Setelah field input, _method_ [[yii\helpers\Html::submitButton()]] |
||||
akan dipanggil untuk me-_render_ tombol pengiriman data. |
||||
|
||||
|
||||
Mari kita uji <span id="trying-it-out"></span> |
||||
------------- |
||||
|
||||
Untuk melihat bagaimana prosesnya, gunakan browser anda untuk mengakses URL ini : |
||||
|
||||
``` |
||||
http://hostname/index.php?r=site%2Fentry |
||||
``` |
||||
|
||||
Anda akan melihat halaman yang menampilkan form dengan dua field input. Dibagian atas dari semua input field, ada label yang menginformasikan data yang mana yang akan diinput. Jika anda menekan tombol pengiriman data tanpa |
||||
menginput apapun, atau anda tidak menginput email address yang tidak valid, anda akan melihat pesan kegagalan yang di tampilkan di bagian bawah field input yang bermasalah. |
||||
|
||||
![Form yang validasinya gagal](images/start-form-validation.png) |
||||
|
||||
Setelah menginput nama dan alamat email yang benar dan menekan tombol kirim, anda akan melihat halaman baru |
||||
yang menampilkan data yang barusan anda input. |
||||
|
||||
![Konfirmasi penginputan data](images/start-entry-confirmation.png) |
||||
|
||||
|
||||
|
||||
### Penjelasan <span id="magic-explained"></span> |
||||
|
||||
Anda mungkin bertanya-tanya bagaimana form HTML bekerja dibelakang layar, sepertinya tampak ajaib karna form tersebut mampu |
||||
menampilkan label di setiap field input dan menampilkan pesan kegagalan jika anda tidak menginput data dengan benar |
||||
tanpa me-_reload_ halaman. |
||||
|
||||
Betul, validasi data sebenarnya dilakukan di sisi klien menggunakan Javascript, dan selanjutnya dilakukan lagi di sisi server menggunakan PHP. |
||||
[[yii\widgets\ActiveForm]] cukup cerdas untuk menerjemahkan pengaturan validasi yang anda deklarasikan pada class `EntryForm`, |
||||
kemudian merubahnya menjadi kode Javascript, dan menggunakan Javascript untuk melakukan validasi data. Jika saja anda menonaktifkan |
||||
Javascript pada browser anda, validasi tetap akan dilakukan di sisi server, sepertinya yang ditunjukkan pada |
||||
_method_ `actionEntry`. Hal ini memastikan bahwa data akan divalidasi dalam segala kondisi. |
||||
|
||||
> Warning: Validasi melalui sisi klien akan membuat pengalaman pengguna lebih baik. Validasi di sisi server |
||||
harus selalu dilakukan, walaupun validasi melalui sisi klien digunakan atau tidak. |
||||
|
||||
Label untuk field input dibuat oleh method `field()`, menggunakan nama _property_ dari model. |
||||
Contoh, label `Name` akan dibuat untuk _property_ `name`. |
||||
|
||||
Anda boleh memodifikasi label di dalam view menggunakan |
||||
kode seperti di bawah ini: |
||||
|
||||
```php |
||||
<?= $form->field($model, 'name')->label('Your Name') ?> |
||||
<?= $form->field($model, 'email')->label('Your Email') ?> |
||||
``` |
||||
|
||||
> Info: Yii menyediakan banyak _widget_ untuk membantu anda dalam membangun _view_ yang kompleks dan dinamis. |
||||
Sebentar lagi anda akan mengetahui, bahwa menulis _widget_ juga sangat mudah. Anda mungkin akan mengganti sebagian besar |
||||
dari kode _view_ anda menjadi _widget-widget_ yang mampu digunakan ulang untuk menyederhanakan penulisan _view_ ke depannya. |
||||
|
||||
|
||||
Rangkuman <span id="summary"></span> |
||||
------- |
||||
|
||||
Pada bagian kali ini, anda telah mengetahui semua bagian dari pola arsitektur MVC. Anda sudah mempelajari bagaimana |
||||
untuk membuat class model sebagai representasi data pengguna dan memvalidasinya. |
||||
|
||||
Anda juga mempelajari bagaimana mengambil data dari pengguna dan bagaimana menampilkan kembali data tersebut ke browser. Pekerjaan seperti ini |
||||
biasanya memakan waktu lama pada saat mengembangkan aplikasi, tetapi Yii menyediakan _widget_ yang bermanfaat |
||||
yang akan membuat pekerjaan ini menjadi lebih mudah. |
||||
|
||||
Di bagian selanjutnya, anda akan mempelajari bagaimana untuk bekerja dengan database, dimana hal tersebut hampir sangat dibutuhkan pada setiap aplikasi. |
@ -0,0 +1,139 @@
|
||||
Membuat Kode menggunakan Gii |
||||
======================== |
||||
|
||||
Bagian ini akan menjelaskan bagaimana cara menggunakan [Gii](https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md) untuk membuat kode secara otomatis |
||||
yang mengimplementasikan fitur-fitur yang bersifat umum dalam sebuah web site. Menggunakan Gii untuk membuat kode sesederhana menginput informasi yang sesuai per satu instruksi seperti yang diterangkan pada halaman web Gii. |
||||
|
||||
Sepanjang bagian ini, anda akan mempelajari bagaimana cara untuk: |
||||
|
||||
* Mengaktifkan Gii pada aplikasi anda, |
||||
* Menggunakan Gii untuk membuat _class ActiveRecord_ |
||||
* Menggunakan Gii untuk membuat kode yang mengoperasikan CRUD untuk database, |
||||
* Memodifikasi kode yang sudah dibuat oleh Gii. |
||||
|
||||
|
||||
Memulai Gii <span id="starting-gii"></span> |
||||
------------ |
||||
|
||||
[Gii](https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md) telah disediakan oleh Yii sebagai [module](structure-modules.md). Anda dapat mengaktifkan Gii |
||||
dengan mengatur konfigurasi Gii pada properti [[yii\base\Application::modules|modules]] dari objek aplikasi. Tergantung bagaimana anda mengatur aplikasi anda, kode di bawah ini sudah disediakan pada file konfigurasi `config/web.php`: |
||||
|
||||
```php |
||||
$config = [ ... ]; |
||||
|
||||
if (YII_ENV_DEV) { |
||||
$config['bootstrap'][] = 'gii'; |
||||
$config['modules']['gii'] = [ |
||||
'class' => 'yii\gii\Module', |
||||
]; |
||||
} |
||||
``` |
||||
|
||||
Konfigurasi di atas menyatakan bahwa, ketika mode [development environment](concept-configurations.md#environment-constants) aktif, |
||||
maka aplikasi harus mengikutkan module yang bernama `gii`, dimana objek tersebut merupakan class [[yii\gii\Module]]. |
||||
|
||||
Jika anda melihat [_entry script_](structure-entry-scripts.md) `web/index.php` pada aplikasi anda, anda akan |
||||
menemukan baris dibawah ini, yang menyatakan secara explisit bahwa `YII_ENV_DEV` sama dengan `true`. |
||||
|
||||
```php |
||||
defined('YII_ENV') or define('YII_ENV', 'dev'); |
||||
``` |
||||
|
||||
Karna baris tersebut, aplikasi anda harusnya sudah berada pada mode _development_, dan secara otomatis mengaktifkan Gii karena konfigurasi sebelumnya. Anda dapat mengakses Gii melalui URL di bawah ini: |
||||
|
||||
``` |
||||
http://hostname/index.php?r=gii |
||||
``` |
||||
|
||||
> Note: Jika anda mengakses Gii melalui komputer diluar komputer localhost anda, secara default akses tidak akan diperbolehkan |
||||
> karna alasan keamanan. Anda dapat mengatur Gii untuk menambah alamat IP yang di perbolehkan seperti ini, |
||||
> |
||||
```php |
||||
'gii' => [ |
||||
'class' => 'yii\gii\Module', |
||||
'allowedIPs' => ['127.0.0.1', '::1', '192.168.0.*', '192.168.178.20'] // adjust this to your needs |
||||
], |
||||
``` |
||||
|
||||
![Gii](images/start-gii.png) |
||||
|
||||
|
||||
Membuat class _Active Record_ <span id="generating-ar"></span> |
||||
--------------------------------- |
||||
|
||||
Untuk menggunakan Gii dalam membuat class Active Record, pilih "Model Generator" (dengan cara mengklik link pada halaman index Gii). Kemudian isi form dengan data berikut: |
||||
|
||||
* Table Name: `country` |
||||
* Model Class: `Country` |
||||
|
||||
![Pembuat Model](images/start-gii-model.png) |
||||
|
||||
Selanjutnya, klik pada tombol "Preview". Anda akan melihat `models/Country.php` pada daftar class yang akan dibuat. Anda bisa mengklik nama dari class tersebut untuk melihat isi kodenya. |
||||
|
||||
Pada saat menggunakan Gii, jika anda sudah membuat file dengan nama yang sama sebelumnya dan akan menimpanya, klik |
||||
tombol `diff` disebelah nama file untuk melihat perbedaan antara kode yang akan dibuat |
||||
dengan kode yang ada saat ini. |
||||
|
||||
![Preview Pembuat Model](images/start-gii-model-preview.png) |
||||
|
||||
Jika akan menimpa file yang sudah ada, centang kotak di sebelah tulisan "overwrite" dan kemudian klik tombol "Generate". Jika anda membuat file baru, anda cukup mengklik tombol "Generate". |
||||
|
||||
Selanjutnya, anda akan melihat |
||||
halaman konfirmasi yang memberitahui bahwa kode berhasil dibuat. Jika sebelumnya anda sudah mempunyai file yang sama, anda juga akan melihat pesan yang memberitahukan bahwa file tersebut sudah ditimpa dengan file yang baru. |
||||
|
||||
|
||||
Membuat CRUD <span id="generating-crud"></span> |
||||
-------------------- |
||||
|
||||
_CRUD_ adalah _Create, Read, Update,_ dan _Delete_, yang merepresentasikan empat tugas umum yang melibatkan website secara umum. Untuk membuat _CRUD_ menggunakan Gii, pilih tombol "CRUD Generator" (dengan cara mengklik pada halaman index Gii). Untuk contoh "negara", isi form yang ditampilkan dengan data berikut: |
||||
|
||||
* Model Class: `app\models\Country` |
||||
* Search Model Class: `app\models\CountrySearch` |
||||
* Controller Class: `app\controllers\CountryController` |
||||
|
||||
![Pembuat CRUD](images/start-gii-crud.png) |
||||
|
||||
Selanjutnya, klik tombol "Preview". Anda akan melihat daftar file-file yang akan dibuat, seperti gambar dibawah ini. |
||||
|
||||
![Preview Pembuat CRUD](images/start-gii-crud-preview.png) |
||||
|
||||
Jika anda sebelumnya sudah membuat file `controllers/CountryController.php` dan |
||||
`views/country/index.php` (pada bagian bekerja dengan database), centang kotak "overwrite" untuk menimpa file tersebut. (File pada bagian bekerja dengan database tidak memiliki dukungan CRUD secara penuh.) |
||||
|
||||
|
||||
Mari kita coba <span id="trying-it-out"></span> |
||||
------------- |
||||
|
||||
Untuk melihat bagaimana proses kerjanya, gunakan browser anda untuk mengakses URL dibawah ini: |
||||
|
||||
``` |
||||
http://hostname/index.php?r=country%2Findex |
||||
``` |
||||
|
||||
Anda akan melihat tabel data yang menampilkan negara dari tabel pada database. Anda dapat mengurutkan tabel, |
||||
atau memfilter dengan menginput pencarian filter pada baris judul kolom. |
||||
|
||||
Disetiap negara yang tampil pada tabel, anda dapat memilih apakah akan melihat (_view_) detail, memperbaharui (_update_), atau menghapus (_delete_) data tersebut, |
||||
anda juga dapat mengklik tombol "Create Country" yang berada di atas tabel tersebut untuk menampilkan form untuk membuat data negara yang baru. |
||||
|
||||
![Tabel data negara](images/start-gii-country-grid.png) |
||||
|
||||
![Memperbaharui data negara](images/start-gii-country-update.png) |
||||
|
||||
Dibawah ini adalah daftar file yang dihasilkan oleh Gii, mungkin saja anda ingin melakukan observasi bagaimana fitur-fitur ini di implementasikan, |
||||
atau melakukan modifikasi terhadap file-file yang dihasilkan: |
||||
|
||||
* Controller: `controllers/CountryController.php` |
||||
* Model: `models/Country.php` dan `models/CountrySearch.php` |
||||
* View: `views/country/*.php` |
||||
|
||||
> Info: Gii di desain agar mudah di modifikasi, dan dikembangkan. Menggunakan Gii |
||||
dapat membuat pengembangan aplikasi anda menjadi lebih cepat. Untuk informasi lebih lanjut, silahkan melihat |
||||
bagian [Gii](https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md). |
||||
|
||||
|
||||
Penutup <span id="summary"></span> |
||||
------- |
||||
|
||||
Pada bagian ini, anda telah mengetahui bagaimana cara menggunakan Gii untuk membuat kode yang mengimplementasikan |
||||
fungsi CRUD secara lengkap dalam mengelola data yang tersimpan pada database. |
@ -0,0 +1,35 @@
|
||||
Menatap ke Depan |
||||
================ |
||||
|
||||
Jika anda membaca sepanjang bab "Mulai", sekarang anda sudah membuat aplikasi dengan Yii. Pada proses ini, anda sudah mempelajari bagaimana mengimplementasikan fitur-fitur umum |
||||
yang dibutuhkan, seperti mengambil data dari pengguna melalui form HTML, mengambil data dari database, dan |
||||
menampilkan data dengan halaman per halaman. Anda juga sudah mempelajari bagaimana menggunakan [Gii](https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md) untuk membuat |
||||
kode secara otomatis. Menggunakan Gii dalam membuat kode, mengubah tugas-tugas pengembangan web yang cukup banyak menjadi satu tugas sederhana, sesederhana mengisi form. |
||||
|
||||
Bagian ini akan merangkum bacaan Yii yang tersedia untuk membantu anda menjadi lebih produktif dalam menggunakan framework ini. |
||||
|
||||
* Dokumentasi |
||||
- [Panduan Definitif](http://www.yiiframework.com/doc-2.0/guide-README.html): |
||||
Sesuai dengan judulnya, panduan ini merincikan bagaimana Yii seharusnya bekerja dan menyediakan petunjuk umum |
||||
tentang menggunakan Yii. Panduan ini sangat-sangat penting, dan panduan ini yang harus anda baca |
||||
sebelum menulis kode Yii. |
||||
- [Referensi Class](http://www.yiiframework.com/doc-2.0/index.html): |
||||
Ini menjelaskan bagaimana menggunakan semua class yang disediakan oleh Yii. Pada umumnya anda akan menggunakan ini ketika anda sedang menulis |
||||
kode dan ingin memahami bagaimana penggunaan _class, method, property_. Sebaiknya anda membaca referensi class ini ketika anda memilik pemahaman dasar tentang seluruh bagian framework. |
||||
- [Artikel Wiki](http://www.yiiframework.com/wiki/?tag=yii2): |
||||
Artikel wiki ditulis oleh para pengguna Yii berdasarkan pengalaman pribadi masing-masing. Kebanyakan dari artikel ini ditulis |
||||
seperti layaknya panduan memasak, dan menunjukkan bagaimana menyelesaikan beberapa masalah dengan menggunakan Yii. Walaupun kualitas artikel-artikel ini |
||||
mungkin tidak selengkap Panduan Definitif, tetapi artikel ini terkadang lebih bermanfaat karna membahas topik yang cukup luas |
||||
dan mungkin mampu menyediakan solusi-solusi yang sederhana. |
||||
- [Buku](http://www.yiiframework.com/doc/) |
||||
* [Extensions](http://www.yiiframework.com/extensions/): |
||||
Yang harus dibanggakan adalah Yii memiliki ribuan library extension yang dibuat oleh pengguna yang dapat dipasang di aplikasi anda dengan mudah, dan akan membuat pengembangan aplikasi anda lebih mudah dan cepat. |
||||
* Komunitas |
||||
- Forum: <http://www.yiiframework.com/forum/> |
||||
- IRC: Kanal #yii di freenode (<irc://irc.freenode.net/yii>) |
||||
- Gitter: <https://gitter.im/yiisoft/yii2> |
||||
- GitHub: <https://github.com/yiisoft/yii2> |
||||
- Facebook: <https://www.facebook.com/groups/yiitalk/> |
||||
- Twitter: <https://twitter.com/yiiframework> |
||||
- LinkedIn: <https://www.linkedin.com/groups/yii-framework-1483367> |
||||
- Stackoverflow: <http://stackoverflow.com/questions/tagged/yii2> |
@ -0,0 +1,119 @@
|
||||
Komponen Aplikasi |
||||
================= |
||||
|
||||
Objek Aplikasi _(Application)_ adalah [service locators](concept-service-locator.md). Objek ini menampung seperangkat |
||||
apa yang kita sebut sebagai *komponen aplikasi* yang menyediakan berbagai layanan untuk menangani proses _request_. Sebagai contoh, |
||||
_component_ `urlManager` bertanggung jawab untuk menentukan _route_ dari _request_ menuju _controller_ yang sesuai; |
||||
_component_ `db` menyediakan layanan terkait database; dan sebagainya. |
||||
|
||||
Setiap _component_ aplikasi memiliki sebuah ID yang mengidentifikasi dirinya secara unik dengan _component_ aplikasi lainnya |
||||
di dalam aplikasi yang sama. Anda dapat mengakses _component_ aplikasi melalui _expression_ berikut ini: |
||||
|
||||
```php |
||||
\Yii::$app->componentID |
||||
``` |
||||
|
||||
Sebagai contoh, anda dapat menggunakan `\Yii::$app->db` untuk mengambil [[yii\db\Connection|koneksi ke DB]], |
||||
dan `\Yii::$app->cache` untuk mengambil [[yii\caching\Cache|cache utama]] yang terdaftar dalam aplikasi. |
||||
|
||||
Sebuah _component_ aplikasi dibuat pertama kali pada saat objek tersebut pertama diakses menggunakan _expression_ di atas. Pengaksesan |
||||
berikutnya akan mengembalikan objek _component_ yang sama. |
||||
|
||||
_Component_ aplikasi bisa merupakan objek apa saja. Anda dapat mendaftarkannya dengan mengatur |
||||
_property_ [[yii\base\Application::components]] pada [konfigurasi aplikasi](structure-applications.md#application-configurations). |
||||
Sebagai contoh, |
||||
|
||||
```php |
||||
[ |
||||
'components' => [ |
||||
// mendaftarkan component "cache" menggunakan nama class |
||||
'cache' => 'yii\caching\ApcCache', |
||||
|
||||
// mendaftaran component "db" menggunakan konfigurasi array |
||||
'db' => [ |
||||
'class' => 'yii\db\Connection', |
||||
'dsn' => 'mysql:host=localhost;dbname=demo', |
||||
'username' => 'root', |
||||
'password' => '', |
||||
], |
||||
|
||||
// mendaftaran component "search" menggunakan anonymous function |
||||
'search' => function () { |
||||
return new app\components\SolrService; |
||||
}, |
||||
], |
||||
] |
||||
``` |
||||
|
||||
> Info: Walaupun anda dapat mendaftarkan _component_ aplikasi sebanyak yang anda inginkan, anda harus bijaksana dalam melakukan hal ini. |
||||
_Component_ aplikasi seperti layaknya variabel global. Menggunakan _component_ aplikasi yang terlalu banyak dapat berpotensi |
||||
membuat kode anda menjadi rumit untuk diujicoba dan dikelola. Dalam banyak kasus, anda cukup membuat _component_ lokal |
||||
dan menggunakannya pada saat diperlukan. |
||||
|
||||
|
||||
## _Bootstrap Components_ <span id="bootstrapping-components"></span> |
||||
|
||||
Seperti yang disebutkan di atas, sebuah _component_ aplikasi akan dibuat ketika _component_ diakses pertama kali. |
||||
Jika tidak diakses sepanjang _request_ diproses, objek tersebut tidak akan dibuat. Terkadang, anda ingin |
||||
membuat objek _component_ aplikasi tersebut untuk setiap _request_, walaupun _component_ tersebut tidak diakses secara eksplisit. |
||||
Untuk melakukannya, anda dapat memasukkan ID _component_ tersebut ke _property_ [[yii\base\Application::bootstrap|bootstrap]] dari objek _Application_. |
||||
|
||||
Sebagai contoh, konfigurasi aplikasi di bawah ini memastikan bahwa objek _component_ `log` akan selalu dibuat disetiap _request_: |
||||
|
||||
```php |
||||
[ |
||||
'bootstrap' => [ |
||||
'log', |
||||
], |
||||
'components' => [ |
||||
'log' => [ |
||||
// Konfigurasi untuk component "log" |
||||
], |
||||
], |
||||
] |
||||
``` |
||||
|
||||
|
||||
## _Component_ Aplikasi Inti <span id="core-application-components"></span> |
||||
|
||||
Yii menentukan seperangkat _component_ aplikasi inti dengan ID tetap dan konfigurasi default. Sebagai contoh, |
||||
_component_ [[yii\web\Application::request|request]] digunakan untuk memperoleh informasi tentang |
||||
_request_ dari pengguna dan merubahnya menjadi [route](runtime-routing.md). _Component_ [[yii\base\Application::db|db]] |
||||
merepresentasikan sebuah koneksi ke database yang bisa anda gunakan untuk menjalankan _query_ ke database. |
||||
Dengan bantuan _component_ inti inilah maka aplikasi Yii bisa menangani _request_ dari pengguna. |
||||
|
||||
Dibawah ini adalah daftar dari _component_ aplikasi inti. Anda dapat mengatur dan memodifikasinya |
||||
seperti _component_ aplikasi pada umumnya. Ketika anda mengatur _component_ aplikasi inti, |
||||
jika anda tidak mendefinisikan _class_-nya, maka _class_ default yang akan digunakan. |
||||
|
||||
* [[yii\web\AssetManager|assetManager]]: mengatur bundel aset _(asset bundles)_ dan publikasi aset _(asset publishing)_. |
||||
Harap melihat bagian [Pengelolaan Aset](structure-assets.md) untuk informasi lebih lanjut. |
||||
* [[yii\db\Connection|db]]: merepresentasikan sebuah koneksi database yang bisa anda gunakan untuk melakukan _query_ ke database. |
||||
Sebagai catatan, ketika anda mengatur _component_ ini, anda harus menentukan nama _class_ dari _component_ dan _property_ lain dari |
||||
_component_ yang dibutuhkan, seperti [[yii\db\Connection::dsn]]. |
||||
Harap melihat bagian [Data Access Objects](db-dao.md) untuk informasi lebih lanjut. |
||||
* [[yii\base\Application::errorHandler|errorHandler]]: menangani error PHP dan _exception_. |
||||
Harap melihat bagian [Menangani Error](runtime-handling-errors.md) untuk informasi lebih lanjut. |
||||
* [[yii\i18n\Formatter|formatter]]: memformat data ketika data tersebut ditampilkan ke pengguna. Sebagai contoh, sebuah angka |
||||
mungkin ditampilkan menggunakan separator ribuan, dan tanggal mungkin diformat dalam format panjang. |
||||
Harap melihat bagian [Memformat Data](output-formatting.md) untuk informasi lebih lanjut. |
||||
* [[yii\i18n\I18N|i18n]]: mendukung penerjemahan dan format pesan _(message)_. |
||||
Harap melihat bagian [Internasionalisasi](tutorial-i18n.md) untuk informasi lebih lanjut. |
||||
* [[yii\log\Dispatcher|log]]: mengelola target log. |
||||
Harap melihat bagian [Log](runtime-logging.md) untuk informasi lebih lanjut. |
||||
* [[yii\swiftmailer\Mailer|mailer]]: mendukung pembuatan dan pengiriman email. |
||||
Harap melihat bagian [Mail](tutorial-mailing.md) untuk informasi lebih lanjut. |
||||
* [[yii\base\Application::response|response]]: merepresentasikan _response_ yang dikirimkan ke pengguna. |
||||
Harap melihat bagian [Response](runtime-responses.md) untuk informasi lebih lanjut. |
||||
* [[yii\base\Application::request|request]]: merepresentasikan _request_ yang diterima dari pengguna. |
||||
Harap melihat bagian [Request](runtime-requests.md) untuk informasi lebih lanjut. |
||||
* [[yii\web\Session|session]]: merepresentasikan informasi _session_. _Component_ ini hanya tersedia pada |
||||
objek [[yii\web\Application|Aplikasi Web]]. |
||||
Harap melihat bagian [Session dan Cookie](runtime-sessions-cookies.md) untuk informasi lebih lanjut. |
||||
* [[yii\web\UrlManager|urlManager]]: mendukung penguraian dan pembuatan URL. |
||||
Harap melihat bagian [Route dan Pembuatan URL](runtime-routing.md) untuk informasi lebih lanjut. |
||||
* [[yii\web\User|user]]: merepresentasikan informasi otentikasi dari pengguna. _Component_ ini hanya tersedia pada |
||||
objek [[yii\web\Application|Aplikasi Web]]. |
||||
Harap melihat bagian [Otentikasi](security-authentication.md) untuk informasi lebih lanjut. |
||||
* [[yii\web\View|view]]: mendukung proses _render view_. |
||||
Harap melihat bagian [View](structure-views.md) untuk informasi lebih lanjut. |
@ -0,0 +1,609 @@
|
||||
Aplikasi |
||||
======== |
||||
|
||||
Aplikasi _(Application)_ adalah objek yang mengelola semua struktur dan siklus dari sistem aplikasi Yii. |
||||
Setiap aplikasi sistem Yii mengandung satu objek aplikasi yang dibuat dalam |
||||
[skrip masuk](structure-entry-scripts.md) dan mampu diakses secara global melalui _expression_ `\Yii::$app`. |
||||
|
||||
> Info: Jika kami mengatakan "sebuah aplikasi", itu bisa diartikan sebagai sebuah objek aplikasi |
||||
atau sebuah sistem aplikasi, tergantung bagaimana konteksnya. |
||||
|
||||
Terdapat dua tipe aplikasi: [[yii\web\Application|Aplikasi Web]] dan |
||||
[[yii\console\Application|Aplikasi Konsol]]. Sesuai dengan namanya, yang pertama bertujuan untuk menangani |
||||
_web request_, sedangkan yang kedua menangani _request_ perintah pada konsol. |
||||
|
||||
|
||||
## Konfigurasi Aplikasi <span id="application-configurations"></span> |
||||
|
||||
Ketika [skrip masuk](structure-entry-scripts.md) membuat objek aplikasi, objek ini akan mengambil dan memuat |
||||
sebuah [array konfigurasi](concept-configurations.md) dan menerapkannya pada objek aplikasi seperti berikut ini: |
||||
|
||||
```php |
||||
require(__DIR__ . '/../vendor/autoload.php'); |
||||
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php'); |
||||
|
||||
// memuat konfigurasi aplikasi |
||||
$config = require(__DIR__ . '/../config/web.php'); |
||||
|
||||
// membuat objek aplikasi & menerapkan konfigurasi |
||||
(new yii\web\Application($config))->run(); |
||||
``` |
||||
|
||||
Seperti layaknya [konfigurasi](concept-configurations.md) normal, konfigurasi aplikasi menentukan bagaimana |
||||
proses inisialisasi _property_ dari objek aplikasi. Karena konfigurasi aplikasi pada umumnya |
||||
sangat kompleks, oleh karena itu konfigurasi tersebut di simpan dalam [file konfigurasi](concept-configurations.md#configuration-files), |
||||
seperti file `web.php` pada contoh di atas. |
||||
|
||||
|
||||
## _Property_ Aplikasi <span id="application-properties"></span> |
||||
|
||||
Terdapat cukup banyak _property_ aplikasi penting yang harus anda atur dalam konfigurasi aplikasi. |
||||
_Property_ ini secara khusus menjelaskan _environment_ yang sedang dijalankan oleh aplikasi. |
||||
Sebagai contoh, aplikasi ingin mengetahui bagaimana cara memuat [controller](structure-controllers.md), |
||||
dimana seharusnya aplikasi menyimpan file-file yang bersifat sementara _(temporary files)_, dll. Kami akan meringkas _property_ tersebut dibawah ini: |
||||
|
||||
|
||||
### _Property_ Wajib <span id="required-properties"></span> |
||||
|
||||
Dalam aplikasi apapun, anda harus menentukan setidaknya dua _property_:[[yii\base\Application::id|id]] |
||||
dan [[yii\base\Application::basePath|basePath]]. |
||||
|
||||
|
||||
#### [[yii\base\Application::id|id]] <span id="id"></span> |
||||
|
||||
_Property_ [[yii\base\Application::id|id]] menentukan ID unik yang membedakan objek aplikasi |
||||
dengan yang lainnya. Ini pada umumnya digunakan secara programatik. Walaupun hal ini bukanlah sebuah keharusan, karena persoalan pertukaran informasi, |
||||
anda sangat direkomendasikan hanya menggunakan karakter alfanumerik ketika menentukan ID dari sebuah aplikasi. |
||||
|
||||
|
||||
#### [[yii\base\Application::basePath|basePath]] <span id="basePath"></span> |
||||
|
||||
_Property_ [[yii\base\Application::basePath|basePath]] menentukan direktori _root_ dari sebuah aplikasi. |
||||
Yaitu direktori yang menyimpan semua sumber kode aplikasi sistem, dan aksesnya diproteksi dari luar. Didalam direktori ini, |
||||
anda akan melihat sub-direktori seperti `models`, `views`, dan `controllers` yang menyimpan sumber kode |
||||
dari pola MVC. |
||||
|
||||
Anda dapat menentukan _property_ [[yii\base\Application::basePath|basePath]] menggunakan _directory path_ |
||||
atau [path alias](concept-aliases.md). Kedua bentuk ini, direktori yang dimaksud harus benar-benar ada, jika tidak maka sebuah _exception_ |
||||
akan di-_throw_. _Path_ akan dinormalkan dengan memanggil _function_ `realpath()`. |
||||
|
||||
_Property_ [[yii\base\Application::basePath|basePath]] pada umumnya digunakan untuk mengambil _path_ penting |
||||
lainnya (contoh _runtime path_). Karna itulah _alias path_ yang dinamakan `@app` disediakan untuk merepresentasikan _path_ |
||||
ini. _Path-path_ lainnya boleh dipanggil menggunakan alias ini (contoh: `@app/runtime` untuk merujuk ke direktori runtime). |
||||
|
||||
|
||||
### _Property_ Penting <span id="important-properties"></span> |
||||
|
||||
_Property_ yang dijelaskan di sub-bagian ini cenderung harus di tentukan karena mereka digunakan secara berbeda |
||||
di lintas aplikasi. |
||||
|
||||
|
||||
#### [[yii\base\Application::aliases|Alias]] <span id="aliases"></span> |
||||
|
||||
_Property_ ini memungkinkan anda untuk menentukan seperangkat [alias](concept-aliases.md) dalam bentuk _array_. |
||||
_Array Key_ merupakan nama alias, dan _Array Value_ adalah definisi path yang dimaksud. |
||||
Sebagai contoh: |
||||
|
||||
```php |
||||
[ |
||||
'aliases' => [ |
||||
'@nama1' => 'path/menuju/ke/path1', |
||||
'@nama2' => 'path/menuju/ke/path2', |
||||
], |
||||
] |
||||
``` |
||||
|
||||
Karna tersedianya _property_ ini, anda bisa menentukan beberapa alias pada konfigurasi aplikasi dibanding |
||||
dengan memanggil _method_ [[Yii::setAlias()]]. |
||||
|
||||
|
||||
#### [[yii\base\Application::bootstrap|bootstrap]] <span id="bootstrap"></span> |
||||
|
||||
_Property_ ini merupakan _property_ yang bermanfaat. _Property_ ini memungkinkan anda untuk menentukan _component_ berbentuk _array_ yang harus |
||||
dijalankan dalam [[yii\base\Application::bootstrap()|proses bootstrap]]. |
||||
Sebagai contoh, jika anda memerintahkan sebuah [module](structure-modules.md) untuk merubah [pengaturan URL](runtime-routing.md), |
||||
anda dapat menyusun ID-nya sebagai elemen dari _property_ ini. |
||||
|
||||
Setiap _component_ yang terdaftar pada _property_ ini dapat ditentukan berdasarkan salah satu dari format berikut ini: |
||||
|
||||
- ID dari _Component_ aplikasi yang ditentukan melalui [component](#components), |
||||
- ID dari _module_ yang ditentukan melalui [module](#modules), |
||||
- Nama _class_, |
||||
- Konfigurasi _array_, |
||||
- _anonymous function_ yang membuat dan mengembalikan _(return)_ sebuah _component_. |
||||
|
||||
Sebagai contoh: |
||||
|
||||
```php |
||||
[ |
||||
'bootstrap' => [ |
||||
// Component ID atau Module ID |
||||
'demo', |
||||
|
||||
// Nama Class |
||||
'app\components\Profiler', |
||||
|
||||
// Konfigurasi dalam bentuk array |
||||
[ |
||||
'class' => 'app\components\Profiler', |
||||
'level' => 3, |
||||
], |
||||
|
||||
// anonymous function |
||||
function () { |
||||
return new app\components\Profiler(); |
||||
} |
||||
], |
||||
] |
||||
``` |
||||
|
||||
> Info: Jika ID _module_ tersebut sama dengan ID _component_ aplikasi, _component_ aplikasi tersebut yang akan dipakai |
||||
> pada saat proses _boostrap_. Jika anda ingin menggunakan _module_, anda dapat menentukannya melalui _anonymous function_ |
||||
> seperti berikut ini: |
||||
> |
||||
> ```php |
||||
> [ |
||||
> function () { |
||||
> return Yii::$app->getModule('user'); |
||||
> }, |
||||
> ] |
||||
> ``` |
||||
|
||||
|
||||
Sepanjang proses _bootstrap_, setiap _component_ akan dibuat objeknya. Jika _class component_ |
||||
mengimplementasikan _method interface_ [[yii\base\BootstrapInterface]], _method_ [[yii\base\BootstrapInterface::bootstrap()|bootstrap()]] dari class tersebut |
||||
juga akan dipanggil. |
||||
|
||||
Salah satu contoh praktis lainnya adalah konfigurasi aplikasi untuk [Template Proyek Dasar](start-installation.md), |
||||
dimana _module_ `debug` dan `gii` ditentukan sebagai _component bootstrap_ ketika aplikasi sedang dijalankan |
||||
dalam mode pengembangan: |
||||
|
||||
```php |
||||
if (YII_ENV_DEV) { |
||||
// penyesuaian konfigurasi untuk environment 'dev' |
||||
$config['bootstrap'][] = 'debug'; |
||||
$config['modules']['debug'] = 'yii\debug\Module'; |
||||
|
||||
$config['bootstrap'][] = 'gii'; |
||||
$config['modules']['gii'] = 'yii\gii\Module'; |
||||
} |
||||
``` |
||||
|
||||
> Note: Menentukan terlalu banyak _component_ pada `bootstrap` akan menurunkan performa dari aplikasi anda, dikarenakan |
||||
_component_ yang sama tersebut harus dijalakan dalam setiap _request_. Jadi gunakanlah _component bootstrap_ dengan bijaksana. |
||||
|
||||
#### [[yii\web\Application::catchAll|catchAll]] <span id="catchAll"></span> |
||||
|
||||
_Property_ ini hanya dikenali oleh [[yii\web\Application|Web applications]]. _Property_ ini menentukan |
||||
sebuah [action dari controller](structure-controllers.md) yang ditugaskan menangani semua _request_ dari pengguna. _Property_ ini biasanya |
||||
digunakan ketika aplikasi dalam mode pemeliharaan _(maintenance)_ yang mengarahkan semua _request_ menuju satu _action_. |
||||
|
||||
Konfigurasinya yaitu sebuah _array_ dimana elemen pertama menentukan _route_ dari _action_. |
||||
Element lainnya _(sepasang key-value)_ menentukan parameter yang akan diteruskan ke _action_. Sebagai contoh: |
||||
|
||||
```php |
||||
[ |
||||
'catchAll' => [ |
||||
'offline/notice', |
||||
'param1' => 'value1', |
||||
'param2' => 'value2', |
||||
], |
||||
] |
||||
``` |
||||
|
||||
> Info: Panel _Debug_ pada _development environment_ tidak akan berfungsi ketika _property_ ini diisi. |
||||
|
||||
#### [[yii\base\Application::components|components]] <span id="components"></span> |
||||
|
||||
_Property_ ini adalah salah satu _property_ yang sangat penting. _Property_ ini memperbolehkan anda mendaftarkan beberapa _component_ |
||||
yang disebut [_component_ aplikasi](structure-application-components.md) yang bisa anda gunakan di tempat lain. Sebagai contoh: |
||||
|
||||
```php |
||||
[ |
||||
'components' => [ |
||||
'cache' => [ |
||||
'class' => 'yii\caching\FileCache', |
||||
], |
||||
'user' => [ |
||||
'identityClass' => 'app\models\User', |
||||
'enableAutoLogin' => true, |
||||
], |
||||
], |
||||
] |
||||
``` |
||||
|
||||
Setiap _component_ aplikasi ditentukan dengan sepasang _key-value_ ke dalam _array_. _Key_ merepresentasikan ID _component_, |
||||
dimana _value_ merepresentasikan nama class dari _component_ atau [konfigurasi _array_](concept-configurations.md). |
||||
|
||||
Anda dapat mendaftaran _component_ apapun ke dalam objek aplikasi, dan nantinya _component_ tersebut dapat diakses secara global |
||||
menggunakan _expression_ `\Yii::$app->componentID`. |
||||
|
||||
Harap membaca bagian [_Component_ Aplikasi](structure-application-components.md) untuk penjelasan lebih lanjut. |
||||
|
||||
|
||||
#### [[yii\base\Application::controllerMap|controllerMap]] <span id="controllerMap"></span> |
||||
|
||||
_Property_ ini memperbolehkan anda untuk melakukan _mapping_ sebuah ID _controller_ ke class _controller_ yang anda inginkan. Secara default, Yii melakukan mapping |
||||
ID _controller_ ke _class controller_ berdasarkan [kaidah yang ditentukan](#controllerNamespace) (Contoh: ID `post` akan di _mapping_ |
||||
ke `app\controllers\PostController`). Dengan menentukan _property_ ini, anda diperbolehkan untuk tidak mengikuti kaidah untuk |
||||
spesifik _controller_. Pada contoh dibawah ini, `account` akan di _mapping_ ke |
||||
`app\controllers\UserController`, sedangkan `article` akan di _mapping_ ke `app\controllers\PostController`. |
||||
|
||||
```php |
||||
[ |
||||
'controllerMap' => [ |
||||
'account' => 'app\controllers\UserController', |
||||
'article' => [ |
||||
'class' => 'app\controllers\PostController', |
||||
'enableCsrfValidation' => false, |
||||
], |
||||
], |
||||
] |
||||
``` |
||||
|
||||
_Key array_ dari _property_ ini merepresentasikan ID _controller_, sedangkan _value_ merepresentasikan nama _class |
||||
yang dimaksud atau [konfigurasi _array_](concept-configurations.md). |
||||
|
||||
|
||||
#### [[yii\base\Application::controllerNamespace|controllerNamespace]] <span id="controllerNamespace"></span> |
||||
|
||||
_Property_ ini menentukan _namespace_ default dimana _class controller_ tersebut harus dicari. Default ke |
||||
`app\controllers`. Jika ID _controller_ adalah `post`, secara kaidah, nama _class controller_-nya (tanpa |
||||
_namespace_) adalah `PostController`, dan `app\controllers\PostController` adalah nama class lengkapnya _(Fully Qualified Class Name)_. |
||||
|
||||
_class controller_ juga boleh disimpan dalam sub-direktori dari direktori yang dimaksud _namespace_ ini. |
||||
Sebagai contoh, jika ada ID _controller_ `admin/post`, nama class lengkap yang dimaksud adalah |
||||
`app\controllers\admin\PostController`. |
||||
|
||||
Sangatlah penting bahwa nama class lengkap dari _controller_ tersebut [bisa di-autoload](concept-autoloading.md) |
||||
dan _namespace_ dari _class controller_ anda cocok dengan nilai dari _property_ ini. Jika tidak, |
||||
anda akan melihat error "Halaman tidak ditemukan" ketika mengakses aplikasi. |
||||
|
||||
Jika saja anda tidak ingin mengikut kaidah-kaidah yang dijelaskan di atas, anda boleh menentukan _property_ |
||||
[controllerMap](#controllerMap). |
||||
|
||||
|
||||
#### [[yii\base\Application::language|language]] <span id="language"></span> |
||||
|
||||
_Property_ ini menentukan bahasa apa yang seharusnya ditampilkan pada konten aplikasi ke pengguna. |
||||
Nilai default dari _property_ ini adalah `en`, yang merupakan Bahasa Inggris. Anda harus menentukan _property_ ini |
||||
jika aplikasi anda menyediakan konten dalam berbagai bahasa. |
||||
|
||||
Nilai dari _property_ ini menentukan banyak aspek dari [internasionalisasi](tutorial-i18n.md), |
||||
termasuk penerjemahan pesan, format tanggal, format penomoran, dll. Sebagai contoh, _widget_ [[yii\jui\DatePicker]] |
||||
akan menggunakan _property_ ini secara _default_ untuk menentukan bahasa apa yang digunakan pada kalender yang ditampilkan dan bagaimana |
||||
format tanggal pada kalender tersebut. |
||||
|
||||
Disarankan agar anda menentukan bahasa dalam format [Tag Bahasa IETF](http://en.wikipedia.org/wiki/IETF_language_tag). |
||||
Sebagai contoh, `en` berarti Bahasa Inggris, sedangkan `en-US` berarti Bahasa Inggris yang digunakan di Amerika Serikat. |
||||
|
||||
Informasi selengkapnya mengenai _property_ ini dapat dipelajari di bagian [Internasionalisasi](tutorial-i18n.md). |
||||
|
||||
|
||||
#### [[yii\base\Application::modules|modules]] <span id="modules"></span> |
||||
|
||||
_Property_ ini menentukan [module](structure-modules.md) apa yang akan digunakan oleh aplikasi. |
||||
|
||||
_Property_ ini ditentukan menggunakan _array_ dari _class class modul_ atau [konfigurasi _array_](concept-configurations.md) dimana _array key_ |
||||
merupakan ID dari _module_ tersebut. Berikut contohnya: |
||||
|
||||
```php |
||||
[ |
||||
'modules' => [ |
||||
// modul "booking" dengan class module yang ditentukan |
||||
'booking' => 'app\modules\booking\BookingModule', |
||||
|
||||
// modul "comment" yang ditentukan menggunakan konfigurasi array |
||||
'comment' => [ |
||||
'class' => 'app\modules\comment\CommentModule', |
||||
'db' => 'db', |
||||
], |
||||
], |
||||
] |
||||
``` |
||||
|
||||
Silahkan melihat bagian [Modules](structure-modules.md) untuk informasi lebih lanjut. |
||||
|
||||
|
||||
#### [[yii\base\Application::name|name]] <span id="name"></span> |
||||
|
||||
_Property_ ini menentukan nama aplikasi yang bisa ditampilkan ke pengguna. Berbeda dengan |
||||
_property_ [[yii\base\Application::id|id]], yang mengharuskan nilainya unik, nilai dari _property_ ini secara umum bertujuan untuk |
||||
keperluan tampilan saja; tidak perlu unik. |
||||
|
||||
Anda tidak perlu menentukan _property_ ini jika memang tidak ada kode anda yang akan menggunakannya. |
||||
|
||||
|
||||
#### [[yii\base\Application::params|params]] <span id="params"></span> |
||||
|
||||
_Property_ ini menentukan parameter berbentuk _array_ yang bisa diakses secara global oleh aplikasi. Dibanding menuliskan secara manual |
||||
angka dan _string_ di kode anda, merupakan hal yang bagus jika anda menentukan hal tersebut sebagai parameter-parameter aplikasi |
||||
di satu tempat yang sama, dan menggunakannya pada tempat dimana dia dibutuhkan. Sebagai contoh, anda mungkin menentukan ukuran _thumbnail_ |
||||
sebagai parameter seperti contoh dibawah ini: |
||||
|
||||
```php |
||||
[ |
||||
'params' => [ |
||||
'thumbnail.size' => [128, 128], |
||||
], |
||||
] |
||||
``` |
||||
|
||||
Kemudian, pada kode dimana anda akan menggunakan ukuran tersebut, anda cukup menggunakannya seperti kode dibawah ini: |
||||
|
||||
```php |
||||
$size = \Yii::$app->params['thumbnail.size']; |
||||
$width = \Yii::$app->params['thumbnail.size'][0]; |
||||
``` |
||||
|
||||
Jika di suatu hari anda memutuskan untuk mengganti ukuran _thumbnail_ tersebut, anda cukup menggantinya di konfigurasi aplikasi; |
||||
anda tidak perlu mengganti di semua kode dimana anda menggunakannya. |
||||
|
||||
|
||||
#### [[yii\base\Application::sourceLanguage|sourceLanguage]] <span id="sourceLanguage"></span> |
||||
|
||||
_Property_ ini menentukan bahasa apa yang digunakan dalam menulis kode aplikasi. Nilai default-nya adalah `'en-US'`, |
||||
yang berarti Bahasa Inggris (Amerika Serikat). Anda sebaiknya menentukan _property_ ini jika teks pada kode anda bukanlah Bahasa Inggris. |
||||
|
||||
Seperti layaknya _property_ [language](#language), anda seharusnya menentukan _property_ ini dalam |
||||
format [Tag Bahasa IETF](http://en.wikipedia.org/wiki/IETF_language_tag). Sebagai contoh, `en` berarti Bahasa Inggris, |
||||
sedangkan `en-US` berarti Bahasa Inggris (Amerika Serikat). |
||||
|
||||
Untuk informasi lebih lanjut mengenai _property_ ini bisa anda pelajari pada bagian [Internasionalisasi](tutorial-i18n.md). |
||||
|
||||
|
||||
#### [[yii\base\Application::timeZone|timeZone]] <span id="timeZone"></span> |
||||
|
||||
_Property_ ini disediakan sebagai cara alternatif untuk menentukan zona waktu default dari _PHP runtime_. |
||||
Dengan menentukan _property_ ini, pada dasarnya anda memanggil _function_ PHP |
||||
[date_default_timezone_set()](http://php.net/manual/en/function.date-default-timezone-set.php). Sebagi contoh: |
||||
|
||||
```php |
||||
[ |
||||
'timeZone' => 'America/Los_Angeles', |
||||
] |
||||
``` |
||||
|
||||
|
||||
#### [[yii\base\Application::version|version]] <span id="version"></span> |
||||
|
||||
_Property_ ini menentukan versi dari aplikasi anda. Secara default nilainya adalah `'1.0'`. Anda tidak harus menentukan |
||||
_property_ ini jika tidak ada kode anda yang akan menggunakannya. |
||||
|
||||
|
||||
### _Property_ yang Bermanfaat <span id="useful-properties"></span> |
||||
|
||||
_Property_ yang dijelaskan pada sub-bagian ini tidak secara umum digunakan karena nilai default-nya |
||||
sudah ditentukan berdasarkan kaidah-kaidah yang umum digunakan. Tetapi anda boleh menentukannya sendiri jikalau anda tidak ingin mengikuti kaidah-kaidah tersebut. |
||||
|
||||
|
||||
#### [[yii\base\Application::charset|charset]] <span id="charset"></span> |
||||
|
||||
_Property_ ini menentukan _charset_ yang digunakan oleh aplikasi. Nilai default-nya adalah `'UTF-8'`, dimana harus |
||||
digunakan sebisa mungkin pada kebanyakan aplikasi, kecuali anda sedang membangun sistem lama yang banyak menggunakan data yang tidak termasuk dalam _Unicode_. |
||||
|
||||
|
||||
#### [[yii\base\Application::defaultRoute|defaultRoute]] <span id="defaultRoute"></span> |
||||
|
||||
_Property_ ini menentukan [route](runtime-routing.md) yang harus aplikasi gunakan ketika sebuah _request_ |
||||
tidak memiliki _route_. _Route_ dapat terdiri dari ID _child module_, ID _controller_, dan/atau ID _action_. |
||||
Sebagai contoh, `help`, `post/create`, atau `admin/post/create`. Jika ID _action_ tidak diberikan, maka _property_ ini akan mengambil |
||||
nilai default yang ditentukan di [[yii\base\Controller::defaultAction]]. |
||||
|
||||
Untuk [[yii\web\Application|aplikasi Web]], nilai default dari _property_ ini adalah `'site'`, yang berarti |
||||
_controller_ `SiteController` dan default _action_-nya yang akan digunakan. Hasilnya, jika anda mengakses |
||||
aplikasi tanpa menentukan _route_ yang spesifik, maka akan menampilkan output dari `app\controllers\SiteController::actionIndex()`. |
||||
|
||||
Untuk [[yii\console\Application|aplikasi konsol]], nilai default-nya adalah `'help'`, yang berarti akan menggunakan |
||||
[[yii\console\controllers\HelpController::actionIndex()]] sebagai perintah utamanya. Hasilnya, jika anda menjalankan perintah `yii` |
||||
tanpa memasukkan argumen, maka akan menampilkan informasi bantuan penggunaan. |
||||
|
||||
|
||||
#### [[yii\base\Application::extensions|extensions]] <span id="extensions"></span> |
||||
|
||||
_Property_ ini menentukan daftar dari [extension](structure-extensions.md) yang terpasang dan digunakan oleh aplikasi. |
||||
Secara default, akan mengambil _array_ yang dikembalikan oleh file `@vendor/yiisoft/extensions.php`. File `extensions.php` |
||||
dibuat dan dikelola secara otomatis jika anda menggunakan [Composer](https://getcomposer.org) untuk memasang _extensions_. |
||||
Secara umum, anda tidak perlu menentukan _property_ ini. |
||||
|
||||
Dalam kasus khusus jika anda ingin mengelola _extension_ secara manual, anda boleh menentukan _property_ ini seperti kode dibawah ini: |
||||
|
||||
```php |
||||
[ |
||||
'extensions' => [ |
||||
[ |
||||
'name' => 'extension name', |
||||
'version' => 'version number', |
||||
'bootstrap' => 'BootstrapClassName', // Tidak wajib, bisa juga berupa konfigurasi array |
||||
'alias' => [ // Tidak Wajib |
||||
'@alias1' => 'to/path1', |
||||
'@alias2' => 'to/path2', |
||||
], |
||||
], |
||||
|
||||
// ... extension lain yang ditentukan seperti kode di atas ... |
||||
|
||||
], |
||||
] |
||||
``` |
||||
|
||||
Seperti yang anda lihat, _property_ ini menerima spesifikasi _extension_ dalam bentuk _array_. Setiap _extension_ ditentukan dengan _array_ |
||||
yang terdiri dari elemen `name` dan `version`. Jika _extension_ harus dijalankan ketika proses [bootstrap](runtime-bootstrapping.md) |
||||
, elemen `bootstrap` dapat dispesifikasikan dengan nama _class bootstrap_-nya atau [konfigurasi array](concept-configurations.md) |
||||
. _Extension_ juga dapat menentukan beberapa [alias](concept-aliases.md). |
||||
|
||||
|
||||
#### [[yii\base\Application::layout|layout]] <span id="layout"></span> |
||||
|
||||
_Property_ ini menentukan nama dari default layout yang akan digunakan ketika me-render sebuah [view](structure-views.md). |
||||
Nilai default-nya adalah `'main'`, yang berarti akan menggunakan file layout `main.php` yang disimpan di [layout path](#layoutPath). |
||||
Jika kedua dari [layout path](#layoutPath) dan [view path](#viewPath) mengambil nilai default, |
||||
maka representasi file layoutnya adalah _path alias_ `@app/views/layouts/main.php`. |
||||
|
||||
Anda dapat menentukan nilai _property_ ini menjadi `false` jika anda ingin menonaktifkan layout secara default, tetapi anda seharusnya tidak memerlukannya. |
||||
|
||||
|
||||
#### [[yii\base\Application::layoutPath|layoutPath]] <span id="layoutPath"></span> |
||||
|
||||
_Property_ ini menentukan path dimana sistem akan mencari file layout. Nilai default-nya adalah |
||||
sub-direktori `layouts` di dalam [view path](#viewPath). Jika [view path](#viewPath) mengambil |
||||
nilai defaultnya, maka path layout defaultnya adalah path alias `@app/views/layouts`. |
||||
|
||||
Anda dapat menentukannya sebagai direktori atau path [alias](concept-aliases.md). |
||||
|
||||
|
||||
#### [[yii\base\Application::runtimePath|runtimePath]] <span id="runtimePath"></span> |
||||
|
||||
_Property_ ini menentukan dimana path file yang bersifat sementara, seperti file _log_ dan _cache_. |
||||
Nilai default-nya adalah direktori yang direpresentasikan oleh alias `@app/runtime`. |
||||
|
||||
Anda dapat menentukan nilainya dengan direktori atau path [alias](concept-aliases.md). Sebagai catatan, _path runtime_ wajib |
||||
memiliki akses tulis _(writeable)_ oleh _web server_ yang menjalankan aplikasi. Dan path tersebut sebaiknya diproteksi aksesnya dari |
||||
pengguna, karena file yang bersifat sementara di dalamnya mungkin mengandung informasi sensitif. |
||||
|
||||
Untuk menyederhanakan akses ke path ini, Yii sudah menentukan path alias dengan nama `@runtime`. |
||||
|
||||
|
||||
#### [[yii\base\Application::viewPath|viewPath]] <span id="viewPath"></span> |
||||
|
||||
_Property_ ini menentukan direktori _root_ dimana file-file _view_ akan disimpan. Nilai default-nya adalah direktori |
||||
yang di representasikan oleh alias `@app/views`. Anda dapat menentukan nilainya dengan direktori atau path [alias](concept-aliases.md). |
||||
|
||||
|
||||
#### [[yii\base\Application::vendorPath|vendorPath]] <span id="vendorPath"></span> |
||||
|
||||
_Property_ ini menentukan direktori _vendor_ yang di kelola oleh [Composer](https://getcomposer.org). Direktori ini akan |
||||
menyimpan semua _library_ pihak ketiga yang digunakan oleh aplikasi anda, termasuk Yii _framework_. Nilai default-nya adalah |
||||
direktori yang di representasikan oleh alias `@app/vendor`. |
||||
|
||||
Anda dapat menentukan nilai _property_ ini dengan direktori atau path [alias](concept-aliases.md). Jika anda mengganti |
||||
nilai _property_ ini, pastikan anda juga menyesuaikan konfigurasi Composer. |
||||
|
||||
Untuk memudahkan akses ke path ini, Yii sudah menentukan path alias dengan nama `@vendor`. |
||||
|
||||
|
||||
#### [[yii\console\Application::enableCoreCommands|enableCoreCommands]] <span id="enableCoreCommands"></span> |
||||
|
||||
_Property_ ini hanya dikenali oleh [[yii\console\Application|console applications]]. _Property_ ini menentukan |
||||
apakah perintah inti yang dibawa oleh rilisan Yii harus diaktifkan. Nilai default-nya adalah `true`. |
||||
|
||||
|
||||
## _Event_ Aplikasi <span id="application-events"></span> |
||||
|
||||
Sebuah objek _aplikasi_ menjalankan beberapa _event_ sepanjang siklus penanganan _request_. Anda dapat menempelkan penanganan _event_ |
||||
untuk _event-event_ ini di dalam konfigurasi aplikasi seperti di bawah ini: |
||||
|
||||
```php |
||||
[ |
||||
'on beforeRequest' => function ($event) { |
||||
// ... |
||||
}, |
||||
] |
||||
``` |
||||
|
||||
Penggunaan dari sintaks `on eventName` akan dijelaskan pada bagian |
||||
[Konfigurasi](concept-configurations.md#configuration-format). |
||||
|
||||
Sebagai alternatif, anda dapat menempelkan penanganan _event_ ke dalam [proses bootstrap](runtime-bootstrapping.md) |
||||
setelah objek aplikasi telah dibuat. Sebagai contoh: |
||||
|
||||
```php |
||||
\Yii::$app->on(\yii\base\Application::EVENT_BEFORE_REQUEST, function ($event) { |
||||
// ... |
||||
}); |
||||
``` |
||||
|
||||
### [[yii\base\Application::EVENT_BEFORE_REQUEST|EVENT_BEFORE_REQUEST]] <span id="beforeRequest"></span> |
||||
|
||||
_Event_ ini dijalankan *sebelum* objek aplikasi menangani sebuah _request_. Nama _event_-nya adalah `beforeRequest`. |
||||
|
||||
Ketika _event_ ini dijalankan, objek aplikasi sudah dibuat dan di inisialisasi. Jadi waktu ini merupakan waktu yang tepat |
||||
untuk memasukkan kode anda melalui mekanisme _event_ untuk mengintervensi penanganan _request_. Sebagai contoh, |
||||
di penanganan _event_, anda dapat menentukan _property_ [[yii\base\Application::language]] secara dinamis berdasarkan parameter tertentu. |
||||
|
||||
|
||||
### [[yii\base\Application::EVENT_AFTER_REQUEST|EVENT_AFTER_REQUEST]] <span id="afterRequest"></span> |
||||
|
||||
_Event_ ini dijalankan *setelah* objek aplikasi menyelesaikan penanganan sebuah _request_ tetapi *sebelum* mengirimkan _response_. |
||||
|
||||
Ketika _event_ ini dijalankan, proses penanganan _request_ sudah selesai dan anda dapat menggunakan kesempatan untuk melakukan beberapa tugas |
||||
untuk memodifikasi _request_ atau _response_. |
||||
|
||||
Sebagai catatan, _component_ [[yii\web\Response|response]] juga menjalankan beberapa _event_ pada saat mengirim |
||||
isi _response_ ke pengguna. _Event_ tersebut akan dijalankan *setelah* _event_ ini. |
||||
|
||||
|
||||
### [[yii\base\Application::EVENT_BEFORE_ACTION|EVENT_BEFORE_ACTION]] <span id="beforeAction"></span> |
||||
|
||||
_Event_ ini dijalankan *sebelum* semua [action dari controller](structure-controllers.md) diproses. |
||||
Nama _event_-nya adalah `beforeAction`. |
||||
|
||||
Parameter _event_ merupakan objek dari [[yii\base\ActionEvent]]. Sebuah penanganan _event_ boleh menentukan |
||||
_property_ [[yii\base\ActionEvent::isValid]] menjadi `false` untuk memberhentikan proses jalannya _action_. |
||||
Sebagai contoh: |
||||
|
||||
```php |
||||
[ |
||||
'on beforeAction' => function ($event) { |
||||
if (kondisi tertentu) { |
||||
$event->isValid = false; |
||||
} else { |
||||
} |
||||
}, |
||||
] |
||||
``` |
||||
|
||||
Sebagai catatan, _event_ `beforeAction` yang sama juga dijalankan oleh [module](structure-modules.md) |
||||
dan [controller](structure-controllers.md). _Event_ pada objek aplikasi yang menjalankan _event_ ini |
||||
untuk pertama kali, dilanjutkan oleh _module_ (jika ada), dan terakhir oleh _controller_. Jika sebuah penanganan _event_ |
||||
menentukan _property_ [[yii\base\ActionEvent::isValid]] menjadi `false`, semua _event_ selanjutnya TIDAK akan dijalankan. |
||||
|
||||
|
||||
### [[yii\base\Application::EVENT_AFTER_ACTION|EVENT_AFTER_ACTION]] <span id="afterAction"></span> |
||||
|
||||
_Event_ ini dijalankan *setelah* menjalankan seluruh [action dari controller](structure-controllers.md). |
||||
Nama _event_-nya adalah `afterAction`. |
||||
|
||||
Parameter _event_ adalah objek dari [[yii\base\ActionEvent]]. Menggunakan |
||||
_property_ [[yii\base\ActionEvent::result]], _method_ penanganan _event_ dapat mengakses atau merubah hasil dari _action_. |
||||
Sebagai contoh: |
||||
|
||||
```php |
||||
[ |
||||
'on afterAction' => function ($event) { |
||||
if (kondisi tertentu) { |
||||
// rubah nilai dari $event->result |
||||
} else { |
||||
} |
||||
}, |
||||
] |
||||
``` |
||||
|
||||
Sebagai catatan, _event_ `afterAction` yang sama juga dijalankan oleh [module](structure-modules.md) |
||||
dan [controllers](structure-controllers.md). Objek-objek ini menjalankan _event_ ini sama seperti `beforeAction`, |
||||
hanya saja urutannya merupakan kebalikan dari urutan di _event_ `beforeAction`. _Controller_ adalah objek pertama yang menjalankan _event_ ini, |
||||
setelah itu _module_ (jika ada), dan terakhir di level aplikasi. |
||||
|
||||
|
||||
## Application Lifecycle <span id="application-lifecycle"></span> |
||||
|
||||
![Siklus Aplikasi](images/application-lifecycle.png) |
||||
|
||||
Ketika [skrip masuk](structure-entry-scripts.md) sedang dijalankan untuk menangani sebuah _request_, |
||||
aplikasi akan melewati proses siklus dibawah ini: |
||||
|
||||
1. Skrip masuk mengambil konfigurasi aplikasi dalam bentuk array. |
||||
2. Skrip masuk membuat objek aplikasi: |
||||
* [[yii\base\Application::preInit()|preInit()]] dipanggil, dimana akan mengatur beberapa _property_ aplikasi |
||||
yang sangat penting seperti [[yii\base\Application::basePath|basePath]]. |
||||
* Mendaftarkan [[yii\base\Application::errorHandler|penanganan error]]. |
||||
* Mengatur _property_ aplikasi. |
||||
* [[yii\base\Application::init()|init()]] dipanggil, yang selanjutnya memanggil |
||||
[[yii\base\Application::bootstrap()|bootstrap()]] untuk menjalankan proses _bootstrap component_. |
||||
3. Skrip masuk memanggil [[yii\base\Application::run()]] untuk menjalankan aplikasi: |
||||
* Menjalankan _event_ [[yii\base\Application::EVENT_BEFORE_REQUEST|EVENT_BEFORE_REQUEST]]. |
||||
* Menangani _request_: memproses _request_ menjadi [route](runtime-routing.md) dan parameter-parameternya; |
||||
membuat objek _module_, _controller_, dan _action_ yang dispesifikasikan oleh _route_; dan menjalankan _action_. |
||||
* Menjalankan _event_ [[yii\base\Application::EVENT_AFTER_REQUEST|EVENT_AFTER_REQUEST]]. |
||||
* Mengirim _response_ ke pengguna. |
||||
4. Skrip masuk mendapatkan _status exit_ dari aplikasi dan menyelesaikan proses penanganan _request_. |
@ -0,0 +1,113 @@
|
||||
Skrip Masuk |
||||
=========== |
||||
|
||||
Skrip masuk adalah langkah pertama pada proses _bootstrap_ aplikasi. Dalam sebuah aplikasi (apakah |
||||
itu aplikasi web atau aplikasi konsol) memiliki satu skrip masuk. Pengguna mengirim _request_ ke |
||||
skrip masuk dimana skrip tersebut membangun objek aplikasi dan meneruskan _request_ ke objek tersebut. |
||||
|
||||
Skrip masuk untuk aplikasi web harus disimpan pada direktori yang dapat diakses dari web sehingga |
||||
dapat di akses oleh pengguna. Secara umum, skrip tersebut diberi nama `index.php`, tetapi boleh menggunakan nama lain, |
||||
selama _web server_ bisa mengakses skrip tersebut. |
||||
|
||||
Skrip masuk untuk aplikasi konsol pada umumnya disimpan di dalam [base path](structure-applications.md) |
||||
dari objek aplikasi dan diberi nama `yii` (dengan suffix `.php`). Skrip tersebut harus memiliki akses _execute_ |
||||
sehingga pengguna dapat menjalan aplikasi konsol menggunakan perintah `./yii <route> [argument] [option]`. |
||||
|
||||
Skrip masuk umumnya mengerjakan tugas berikut ini: |
||||
|
||||
* Menentukan _global constant_; |
||||
* Mendaftarkan [autoloader Composer](https://getcomposer.org/doc/01-basic-usage.md#autoloading); |
||||
* Memasukkan file _class_ [[Yii]]; |
||||
* Mengambil konfigurasi aplikasi, dan memuatnya; |
||||
* Membuat dan mengatur objek [application](structure-applications.md); |
||||
* Memanggil [[yii\base\Application::run()]] untuk memproses _request_ yang diterima; |
||||
|
||||
|
||||
## Aplikasi Web<span id="web-applications"></span> |
||||
|
||||
Kode berikut ini adalah kode yang terdapat pada skrip masuk [Template Proyek Dasar](start-installation.md). |
||||
|
||||
```php |
||||
<?php |
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true); |
||||
defined('YII_ENV') or define('YII_ENV', 'dev'); |
||||
|
||||
// mendaftarkan autoloader Composer |
||||
require(__DIR__ . '/../vendor/autoload.php'); |
||||
|
||||
// memasukkan file class Yii |
||||
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php'); |
||||
|
||||
// Mengambil konfigurasi aplikasi |
||||
$config = require(__DIR__ . '/../config/web.php'); |
||||
|
||||
// Membuat, mengkonfigurasi, dan menjalankan aplikasi |
||||
(new yii\web\Application($config))->run(); |
||||
``` |
||||
|
||||
|
||||
## Aplikasi Konsol <span id="console-applications"></span> |
||||
|
||||
Demikian juga dengan aplikasi konsol, kode berikut ini adalah kode yang terdapat pada skrip masuk aplikasi konsol : |
||||
|
||||
```php |
||||
#!/usr/bin/env php |
||||
<?php |
||||
/** |
||||
* Yii console bootstrap file. |
||||
* |
||||
* @link http://www.yiiframework.com/ |
||||
* @copyright Copyright (c) 2008 Yii Software LLC |
||||
* @license http://www.yiiframework.com/license/ |
||||
*/ |
||||
|
||||
defined('YII_DEBUG') or define('YII_DEBUG', true); |
||||
defined('YII_ENV') or define('YII_ENV', 'dev'); |
||||
|
||||
// mendaftarkan autoloader composer |
||||
require(__DIR__ . '/vendor/autoload.php'); |
||||
|
||||
// memasukkan file class Yii |
||||
require(__DIR__ . '/vendor/yiisoft/yii2/Yii.php'); |
||||
|
||||
// Mengambil konfigurasi aplikasi |
||||
$config = require(__DIR__ . '/config/console.php'); |
||||
|
||||
$application = new yii\console\Application($config); |
||||
$exitCode = $application->run(); |
||||
exit($exitCode); |
||||
``` |
||||
|
||||
|
||||
## Menentukan _Constant_ <span id="defining-constants"></span> |
||||
|
||||
Skrip masuk adalah file yang tepat untuk menentukan _global constant_. Yii mengenali tiga _constant_ berikut ini: |
||||
|
||||
* `YII_DEBUG`: untuk menentukan apakah aplikasi sedang dalam mode _debug_. Pada saat mode _debug_, aplikasi |
||||
akan menyimpan informasi log lebih banyak, dan akan menampilkan detail error urutan pemanggilan _(error call stack)_ jika ada _exception_ yang di-_throw_. Alasan inilah, |
||||
kenapa mode _debug_ sebaiknya digunakan pada tahap pengembangan. Nilai _default_ dari `YII_DEBUG` adalah `false`. |
||||
* `YII_ENV`: untuk menentukan pada mode _environment_ manakah aplikasi ini dijalankan. _Constant_ ini akan dijelaskan lebih lanjut di |
||||
bagian [Konfigurasi](concept-configurations.md#environment-constants). |
||||
Nilai _default_ dari `YII_ENV` adalah `prod`, yang berarti aplikasi sedang dijalankan pada _production environment_. |
||||
* `YII_ENABLE_ERROR_HANDLER`: untuk menentukan apakah akan mengaktifkan penanganan eror yang disediakan oleh Yii. Nilai _default_ |
||||
dari _constant_ ini adalah `true`. |
||||
|
||||
Untuk menentukan _constant_, kita biasanya menggunakan kode berikut ini: |
||||
|
||||
```php |
||||
defined('YII_DEBUG') or define('YII_DEBUG', true); |
||||
``` |
||||
|
||||
kode di atas memiliki tujuan yang sama dengan kode berikut ini: |
||||
|
||||
```php |
||||
if (!defined('YII_DEBUG')) { |
||||
define('YII_DEBUG', true); |
||||
} |
||||
``` |
||||
|
||||
Jelas, kode yang pertama lah yang lebih ringkas dan lebih mudah untuk dimengerti. |
||||
|
||||
Penentuan _constant_ sebaiknya ditulis di baris-baris awal pada skrip masuk sehingga akan berfungsi |
||||
ketika file PHP lain akan dimasukkan _(include)_. |
@ -0,0 +1,26 @@
|
||||
Tinjauan |
||||
======== |
||||
|
||||
Aplikasi Yii diorganisir berdasarkan pola arsitektur [model-view-controller (MVC)](http://wikipedia.org/wiki/Model-view-controller). |
||||
[Model](structure-models.md) merepresentasikan data, pengaturan dan proses bisnis; [view](structure-views.md) |
||||
adalah output yang merepresentasikan model; dan [controller](structure-controllers.md) mengelola input dan merubahnya |
||||
menjadi perintah-perintah untuk [model](structure-models.md) dan [view](structure-views.md). |
||||
|
||||
Selain MVC, aplikasi Yii juga memiliki entitas berikut: |
||||
|
||||
* [entry scripts](structure-entry-scripts.md): Ini adalah skrip PHP yang diakses secara langsung oleh pengguna. |
||||
Ini bertugas untuk memulai siklus penanganan _request_. |
||||
* [applications](structure-applications.md): Ini adalah objek yang dapat diakses secara global, yang mengelola _component_ aplikasi |
||||
dan mengaturnya untuk memenuhi sebuah _request_. |
||||
* [application components](structure-application-components.md): Ini adalah objek-objek yang didaftarkan pada objek _application_ dan |
||||
menyediakan beragam layanan untuk memenuhi _request_. |
||||
* [modules](structure-modules.md): Ini adalah paket _(package)_ mandiri yang berisikan MVC lengkap. |
||||
Sebuah aplikasi boleh diistilahkan sebagai module-module yang telah diorganisir. |
||||
* [filters](structure-filters.md): Ini merepresentaikan kode yang mutlak untuk dijalakan sebelum dan sesudah |
||||
penanganan dari tiap-tiap _request_ yang dikelola oleh _controller_. |
||||
* [widgets](structure-widgets.md): Ini adalah objek-objek yang dapat ditanam kedalam [views](structure-views.md). Ini |
||||
dapat mengandung logika _controller_ dan dapat digunakan berulang-ulang pada _view_ yang berbeda. |
||||
|
||||
Diagram dibawah ini menunjukkan struktur statis dari sebuah aplikasi: |
||||
|
||||
![Struktur Statis Aplikasi](images/application-structure.png) |
@ -0,0 +1,6 @@
|
||||
[ |
||||
"Misbahul D. Munir", |
||||
"Muhammad Cahya", |
||||
"Seto Kuslaksono", |
||||
"Novrian Y.F." |
||||
] |
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue