Creating a new project
Let's imagine I've created a yii-apps directory to put all my Yii tests in.cd yii-apps
If I run the following :
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
I'm doing a number of things:
- Using composer with the create-project command.
- Adding the --prefer-dist option to the create-project command which will install packages from dist directory when available.
- Adding the --stability=dev option, so that the app will be created as a piece of development rather than production. That can come later.
- Creating the app using the 'Yii 2.0 Basic Application Template'. There are many application templates you can use. Some of them are written by 'yiisoft', the organisation which develops Yii itself.
Once installed, you can use the following command to see you application.
php yii serve
This would give you a URL such as http://localhost:8080/
Alternatively, if you already have a LAMP server running, you can use a URL like this in your browser:
http://localhost/test/yii-apps/basic/web/
How is it structured?
Yii applications are loaded using the following hierarchy:Entry script -> Controller -> Actions
Yii Views are HTML with PHP. You can use helpers such as yii\helpers\Html and widgets such as yii\widgets\ActiveForm to create views
Yii models use the "active record pattern (methods)" to pull and push data, so in most cases you won't need to write queries.
You can use composer to perform tasks on your application such as create it, or add components.
composer.json handles all the components
config/web.php handles all the routing. Here, you can uncomment the urlManager section to handle pretty URLs.
controllers/SiteController.php is the default controller and contains a method call actionIndex(). This takes users to the index view residing at views/site/index.php. This is where the naming convention becomes obvious. Our controller is called SiteController.php and it corresponds to views/site.
web is the directory containing all the CSS and images etc.
vendor is the directory containing all the libraries.
A full description of the directory structure can be found at https://www.yiiframework.com/doc/guide/2.0/en/start-workflow
One final tip
Since PHP 7 came out you can require multiple namespace items as below:use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};