Browse Source
Conflicts: framework/UPGRADE.md framework/base/Security.php framework/caching/Cache.php framework/caching/XCache.php framework/db/QueryBuilder.php framework/db/Schema.php framework/db/mssql/QueryBuilder.php framework/validators/Validator.php framework/web/UrlManager.php tests/framework/mutex/FileMutexTest.phptags/3.0.0-alpha1
SilverFire - Dmitry Naumenko
8 years ago
429 changed files with 5395 additions and 2871 deletions
@ -0,0 +1,85 @@
|
||||
Obtención de datos para los modelos de múltiples |
||||
================================ |
||||
|
||||
Cuando se trata de algunos datos complejos, es posible que puede que tenga que utilizar varios modelos diferentes para recopilar |
||||
la entrada del usuario. Por ejemplo, suponiendo que la información de inicio de sesión del usuario se almacena en la tabla `user`, |
||||
mientras que el perfil de usuario la información se almacena en la tabla `Profile`, es posible que desee para recoger los datos |
||||
de entrada sobre un usuario a través de un modelo `User` y un modelo `Profile`. Con el modelo de Yii y apoyo formulario, |
||||
puede solucionar este problema de una manera que no es mucho diferente de la manipulación de un solo modelo. |
||||
|
||||
En lo que sigue, vamos a mostrar cómo se puede crear un formulario que permitirá recoger datos tanto para los modelos `User` y |
||||
`Profile`. |
||||
|
||||
En primer lugar, la acción del controlador para la recogida de los datos del usuario y del perfil se puede escribir de la |
||||
siguiente manera, |
||||
|
||||
```php |
||||
namespace app\controllers; |
||||
|
||||
use Yii; |
||||
use yii\base\Model; |
||||
use yii\web\Controller; |
||||
use yii\web\NotFoundHttpException; |
||||
use app\models\User; |
||||
use app\models\Profile; |
||||
|
||||
class UserController extends Controller |
||||
{ |
||||
public function actionUpdate($id) |
||||
{ |
||||
$user = User::findOne($id); |
||||
if (!$user) { |
||||
throw new NotFoundHttpException("The user was not found."); |
||||
} |
||||
|
||||
$profile = Profile::findOne($user->profile_id); |
||||
|
||||
if (!$profile) { |
||||
throw new NotFoundHttpException("The user has no profile."); |
||||
} |
||||
|
||||
$user->scenario = 'update'; |
||||
$profile->scenario = 'update'; |
||||
|
||||
if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post())) { |
||||
$isValid = $user->validate(); |
||||
$isValid = $profile->validate() && $isValid; |
||||
if ($isValid) { |
||||
$user->save(false); |
||||
$profile->save(false); |
||||
return $this->redirect(['user/view', 'id' => $id]); |
||||
} |
||||
} |
||||
|
||||
return $this->render('update', [ |
||||
'user' => $user, |
||||
'profile' => $profile, |
||||
]); |
||||
} |
||||
} |
||||
``` |
||||
|
||||
En la acción `update`, primero cargamos los modelos `User` y `Profile` que se actualicen desde la base de datos. Luego llamamos |
||||
[[yii\base\Model::load()]] para llenar estos dos modelos con la entrada del usuario. Si tiene éxito, se validará |
||||
los dos modelos y guardarlos. De lo contrario vamos a renderizar la vista `update` que tiene el siguiente contenido: |
||||
|
||||
```php |
||||
<?php |
||||
use yii\helpers\Html; |
||||
use yii\widgets\ActiveForm; |
||||
|
||||
$form = ActiveForm::begin([ |
||||
'id' => 'user-update-form', |
||||
'options' => ['class' => 'form-horizontal'], |
||||
]) ?> |
||||
<?= $form->field($user, 'username') ?> |
||||
|
||||
...other input fields... |
||||
|
||||
<?= $form->field($profile, 'website') ?> |
||||
|
||||
<?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?> |
||||
<?php ActiveForm::end() ?> |
||||
``` |
||||
|
||||
Como se puede ver, en el `update` vista que haría que los campos de entrada utilizando dos modelos `User` y `Profile`. |
@ -0,0 +1,131 @@
|
||||
Aliasy |
||||
====== |
||||
|
||||
Aliasy używane są do reprezentowania ścieżek do plików lub adresów URL i pozwalają uniknąć konieczności wielokrotnego definiowania ich |
||||
w kodzie aplikacji. Alias musi zaczynać się od znaku `@`, dla odróżnienia od zwykłej ścieżki i adresu URL. W przypadku zdefiniowania |
||||
aliasu bez tego znaku, będzie on automatycznie dodany na początku. |
||||
|
||||
Yii korzysta z wielu predefiniowanych aliasów. Dla przykładu, alias `@yii` reprezentuje ścieżkę instalacji frameworka, a `@web` bazowy |
||||
adres URL aktualnie uruchomionej aplikacji Web. |
||||
|
||||
Definiowanie aliasów <span id="defining-aliases"></span> |
||||
-------------------- |
||||
|
||||
Możesz zdefiniować alias do ścieżki pliku lub adresu URL wywołując [[Yii::setAlias()]]: |
||||
|
||||
```php |
||||
// alias do ścieżki pliku |
||||
Yii::setAlias('@foo', '/path/to/foo'); |
||||
|
||||
// alias do adresu URL |
||||
Yii::setAlias('@bar', 'http://www.example.com'); |
||||
``` |
||||
|
||||
> Note: *nie* jest konieczne, aby aliasowana ścieżka pliku lub URL wskazywał istniejący plik lub zasób. |
||||
|
||||
Mając już zdefiniowany alias, możesz rozbudować go, tworząc nowy alias (bez konieczności wywołania [[Yii::setAlias()]]), dodając |
||||
ukośnik `/` i kolejne segmenty ścieżki. Aliasy zdefiniowane za pomocą [[Yii::setAlias()]] nazywane są *bazowymi aliasami*, a te, które |
||||
je rozbudowują *aliasami pochodnymi*. Dla przykładu, `@foo` jest aliasem bazowym, a `@foo/bar/file.php` pochodnym. |
||||
|
||||
Możesz definiować aliasy używając innych aliasów (zarówno bazowych, jak i pochodnych): |
||||
|
||||
```php |
||||
Yii::setAlias('@foobar', '@foo/bar'); |
||||
``` |
||||
|
||||
Aliasy bazowe są zwykle definiowane podczas fazy [bootstrappingu](runtime-bootstrapping.md). |
||||
Możliwe jest wywołanie [[Yii::setAlias()]] już w [skrypcie wejściowym](structure-entry-scripts.md). |
||||
[Aplikacja](structure-applications.md) dla wygody deweloperów posiada właściwość `aliases`, którą można zmodyfikować |
||||
w [konfiguracji](concept-configurations.md): |
||||
|
||||
```php |
||||
return [ |
||||
// ... |
||||
'aliases' => [ |
||||
'@foo' => '/path/to/foo', |
||||
'@bar' => 'http://www.example.com', |
||||
], |
||||
]; |
||||
``` |
||||
|
||||
|
||||
Rozwiązywanie aliasów <span id="resolving-aliases"></span> |
||||
--------------------- |
||||
|
||||
Możesz wywołać [[Yii::getAlias()]], aby rozwiązać alias, czyli zamienić go na ścieżkę pliku lub adres URL, który reprezentuje. |
||||
Dotyczy to zarówno bazowych aliasów, jak i pochodnych: |
||||
|
||||
```php |
||||
echo Yii::getAlias('@foo'); // wyświetla: /path/to/foo |
||||
echo Yii::getAlias('@bar'); // wyświetla: http://www.example.com |
||||
echo Yii::getAlias('@foo/bar/file.php'); // wyświetla: /path/to/foo/bar/file.php |
||||
``` |
||||
|
||||
Ścieżka/URL reprezentowany przez pochodny alias jest ustalany poprzez zamianę części z bazowym aliasem na jego rozwiązaną |
||||
reprezentację. |
||||
|
||||
> Note: Metoda [[Yii::getAlias()]] nie sprawdza, czy reprezentowana ścieżka/URL wskazuje na istniejący plik lub zasób. |
||||
|
||||
|
||||
Alias bazowy może również zawierać ukośnik `/`. Metoda [[Yii::getAlias()]] potrafi określić, która część aliasu jest aliasem bazowym |
||||
i prawidłowo określić odpowiadającą mu ścieżkę pliku lub URL: |
||||
|
||||
```php |
||||
Yii::setAlias('@foo', '/path/to/foo'); |
||||
Yii::setAlias('@foo/bar', '/path2/bar'); |
||||
Yii::getAlias('@foo/test/file.php'); // wyświetla: /path/to/foo/test/file.php |
||||
Yii::getAlias('@foo/bar/file.php'); // wyświetla: /path2/bar/file.php |
||||
``` |
||||
|
||||
Gdyby `@foo/bar` nie był zdefiniowany jako bazowy alias, ostatnia instrukcja wyświetliłaby `/path/to/foo/bar/file.php`. |
||||
|
||||
|
||||
Korzystanie z aliasów <span id="using-aliases"></span> |
||||
--------------------- |
||||
|
||||
Aliasy są rozwiązywane automatycznie w wielu miejscach w Yii bez konieczności wywołania bezpośrednio metody [[Yii::getAlias()]]. |
||||
Przykładowo, [[yii\caching\FileCache::cachePath]] akceptuje zarówno ścieżkę pliku, jak i alias ją reprezentujący, odróżniając je |
||||
od siebie dzięki prefiksowi `@`. |
||||
|
||||
```php |
||||
use yii\caching\FileCache; |
||||
|
||||
$cache = new FileCache([ |
||||
'cachePath' => '@runtime/cache', |
||||
]); |
||||
``` |
||||
|
||||
Aby sprawdzić, czy dana właściwość lub parametr metody wspierają użycie aliasów, zapoznaj się z dokumentacją API. |
||||
|
||||
|
||||
Predefiniowane aliasy <span id="predefined-aliases"></span> |
||||
--------------------- |
||||
|
||||
Yii predefiniuje zestaw aliasów do łatwego wskazywania często używanych ścieżek plików i adresów URL: |
||||
|
||||
- `@yii`, folder, w którym znajduje się plik `BaseYii.php` (nazywany także folderem frameworka). |
||||
- `@app`, [[yii\base\Application::basePath|bazowa ścieżka]] aktualnie używanej aplikacji. |
||||
- `@runtime`, [[yii\base\Application::runtimePath|ścieżka cyklu życia]] aktualnie używanej aplikacji. Domyślnie wskazuje na |
||||
`@app/runtime`. |
||||
- `@webroot`, folder bazowy Web aktualnie używanej aplikacji Web. Określany jest jako lokalizacja folderu zawierającego |
||||
[skrypt wejścia](structure-entry-scripts.md). |
||||
- `@web`, bazowy adres URL aktualnie używanej aplikacji Web. Wskazuje na tą samą wartość co [[yii\web\Request::baseUrl]]. |
||||
- `@vendor`, [[yii\base\Application::vendorPath|folder pakietów composera]]. Domyślnie wskazuje na `@app/vendor`. |
||||
- `@bower`, bazowy folder zawierający [pakiety bowera](http://bower.io/). Domyślnie wskazuje na `@vendor/bower`. |
||||
- `@npm`, bazowy folder zawierający [pakiety npm](https://www.npmjs.org/). Domyślnie wskazuje na `@vendor/npm`. |
||||
|
||||
Alias `@yii` jest definiowany poprzez dołączenie pliku `Yii.php` w [skrypcie wejścia](structure-entry-scripts.md). |
||||
Pozostałe aliasy są definiowane w konstruktorze aplikacji podczas ładowania [konfiguracji](concept-configurations.md). |
||||
|
||||
|
||||
Aliasy rozszerzeń <span id="extension-aliases"></span> |
||||
----------------- |
||||
|
||||
Instalacja [rozszerzenia](structure-extensions.md) za pomocą composera automatycznie definiuje dla niego alias. |
||||
Każdy z takich aliasów jest nazwany zgodnie z bazową przestrzenią nazw rozszerzenia określonej w swoim pliku `composer.json` |
||||
i reprezentuje bazowy folder pakietu. Dla przykładu, instalując rozszerzenie `yiisoft/yii2-jui` automatycznie uzyskasz alias |
||||
`@yii/jui` zdefiniowany podczas fazy [bootstrappingu](runtime-bootstrapping.md), będący odpowiednikiem wywołania: |
||||
|
||||
```php |
||||
Yii::setAlias('@yii/jui', 'VendorPath/yiisoft/yii2-jui'); |
||||
``` |
@ -0,0 +1,89 @@
|
||||
Autoładowanie klas |
||||
================== |
||||
|
||||
Yii opiera się na [mechanizmie automatycznego ładowania klas](http://www.php.net/manual/pl/language.oop5.autoload.php) służącym do |
||||
zlokalizowania i dołączenia wszystkich wymaganych plików klas. Wbudowany wysoce wydajny autoloader klas, zgodny ze |
||||
[standardem PSR-4](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-4-autoloader.md), jest instalowany po załączeniu |
||||
pliku `Yii.php`. |
||||
|
||||
> Note: Dla uproszczenia opisów, w tej sekcji zostanie omówione jedynie autoładowanie klas. Należy mieć jednak na uwadze, że poniższe |
||||
informacje odnoszą się również do autoładowania interfejsów i traitów. |
||||
|
||||
|
||||
Korzystanie z autoloadera Yii <span id="using-yii-autoloader"></span> |
||||
----------------------------- |
||||
|
||||
Aby skorzystać z autoloadera klas Yii, powinieneś przestrzegać dwóch prostych zasad tworzenia i nazywania własnych klas: |
||||
|
||||
* Każda klasa musi znajdować się w [przestrzeni nazw](http://php.net/manual/pl/language.namespaces.php) (np. `foo\bar\MyClass`) |
||||
* Każda klasa musi być zapisana jako oddzielny plik, do którego ścieżka określona jest poniższym algorytmem: |
||||
|
||||
```php |
||||
// $className jest w pełni uściśloną nazwą klasy bez początkowego odwrotnego ukośnika |
||||
$classFile = Yii::getAlias('@' . str_replace('\\', '/', $className) . '.php'); |
||||
``` |
||||
|
||||
Przykładowo, jeśli nazwa klasy i przestrzeń nazw to `foo\bar\MyClass`, odpowiadającym ścieżce pliku klasy [aliasem](concept-aliases.md) |
||||
jest `@foo/bar/MyClass.php`. Aby ten alias mógł być przetłumaczony na ścieżkę pliku, `@foo` lub `@foo/bar` musi być |
||||
[aliasem bazowym](concept-aliases.md#defining-aliases). |
||||
|
||||
Używając [podstawowego szablonu projektu](start-installation.md), możesz umieścić swoje klasy w bazowej przestrzeni nazw `app`, dzięki |
||||
czemu mogą być autoładowane przez Yii bez potrzeby definiowania nowego aliasu. Dzieje się tak dzięki temu, że `@app` jest |
||||
[predefiniowanym aliasem](concept-aliases.md#predefined-aliases) i klasa `app\components\MyClass` może być odszukana w pliku |
||||
`AppBasePath/components/MyClass.php`, zgodnie z opisanym algorytmem. |
||||
|
||||
W [zaawansowanym szablonie projektu](https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/README.md) każdy poziom |
||||
aplikacji posiada swój własny bazowy alias. Dla przykładu, front-end określony jest przez bazowy alias `@frontend`, a back-end - |
||||
`@backend`. Dzięki temu możesz umieścić klasy front-endu w przestrzeni nazw `frontend`, a klasy back-endu w przestrzeni nazw `backend`. |
||||
Wszystkie te klasy będą automatycznie załadowane przez autoloader Yii. |
||||
|
||||
|
||||
Mapa klas <span id="class-map"></span> |
||||
--------- |
||||
|
||||
Autoloader klas Yii wspiera mechanizm *mapy klas*, która mapuje nazwy klas do odpowiadających im ścieżek plików. |
||||
Kiedy autoloader ładuje klasę, najpierw sprawdza czy klasa znajduje się w mapie. Jeśli tak, odpowiadająca nazwie ścieżka pliku zostanie |
||||
dołączona od razu, bez dalszej weryfikacji, co jest powodem, dla którego autoładowanie klas jest błyskawiczne. Wszystkie podstawowe |
||||
klasy Yii są autoładowane właśnie w ten sposób. |
||||
|
||||
Możesz dodać klasę do mapy klas, przechowywanej w `Yii::$classMap`, za pomocą instrukcji: |
||||
|
||||
```php |
||||
Yii::$classMap['foo\bar\MyClass'] = 'path/to/MyClass.php'; |
||||
``` |
||||
|
||||
Do określenia ścieżek plików klas można użyć [aliasów](concept-aliases.md). Zapisywanie mapy klas powinno odbywać się w procesie |
||||
[bootstrappingu](runtime-bootstrapping.md), aby mapa była gotowa zanim rozpocznie się korzystanie z klas. |
||||
|
||||
|
||||
Korzystanie z innych autoloaderów <span id="using-other-autoloaders"></span> |
||||
--------------------------------- |
||||
|
||||
Ponieważ Yii opiera się głównie na composerze, jako menedżerze pakietów zależności, zalecane jest również zainstalowanie autoloadera |
||||
composera. Jeśli używasz zewnętrznych bibliotek, korzystających z własnych autoloaderów, powinieneś również je zainstalować. |
||||
|
||||
Używając autoloadera Yii razem z innymi autoloaderami, powinieneś dołączyć plik `Yii.php` *po* wszystkich pozostałych autoloaderach. Dzięki temu |
||||
autoloader Yii jako pierwszy odpowie na żądanie autoładowania klasy. Dla przykładu, poniższy kod znajduje się |
||||
w [skrypcie wejściowym](structure-entry-scripts.md) [podstawowego szablonu projektu](start-installation.md). Pierwsza linia jest |
||||
instrukcją instalacji autoloadera composera, a druga instaluje autoloader Yii: |
||||
|
||||
```php |
||||
require(__DIR__ . '/../vendor/autoload.php'); |
||||
require(__DIR__ . '/../vendor/yiisoft/yii2/Yii.php'); |
||||
``` |
||||
|
||||
Możesz używać jedynie autoloadera composera bez autoloadera Yii, ale wydajność autoładowania klas może być wtedy obniżona i, dodatkowo, |
||||
musisz przestrzegać zasad ustalonych przez composera, aby Twoje klasy mogły być autoładowane. |
||||
|
||||
> Info: Jeśli nie chcesz korzystać z autoloadera Yii, musisz stworzyć swoją własną wersję pliku `Yii.php` i dołączyć ją |
||||
w [skrypcie wejściowym](structure-entry-scripts.md). |
||||
|
||||
|
||||
Autoładowanie klas rozszerzeń <span id="autoloading-extension-classes"></span> |
||||
----------------------------- |
||||
|
||||
Autoloader Yii potrafi również automatycznie ładować klasy [rozszerzeń](structure-extensions.md). Jedynym wymaganiem ze strony |
||||
rozszerzenia jest prawidłowy zapis sekcji `autoload` w swoim pliku `composer.json`. Szczegóły na temat specyfikacji `autoload` znajdują |
||||
się [dokumentacji composera](https://getcomposer.org/doc/04-schema.md#autoload). |
||||
|
||||
Jeśli nie korzystasz z autoloadera Yii, autoloader composera załaduje dla Ciebie automatycznie klasy rozszerzeń. |
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue