How to Install Yii on Windows or a Mac

Want to know more about Yii? Read Introduction to the Yii Framework and follow our Yii Programming series.

How to Install Yii on Windows or a Mac

How to Install Yii on Windows or a Mac

Welcome

In today’s tutorial, we’ll explain how to install Yii in a local development environment for both Windows and macOS. For the Windows guide, we’ll rely on WAMP Server, a Windows web development environment for Apache, PHP and Mac, and for the Mac guide, we’ll use its cousin, MAMP. Although Rod uses WAMP in today’s tutorial, there is also a Windows version of MAMP.

I’m writing the Mac portion of this guide, and my colleague Rod Ussing is writing the Windows side. I met Rod in high school in California at my second programming job, a very large hexadecimal number in years ago. He still uses Windows, but after eight years of working at Microsoft and tiring of rebooting the system to restart Outlook, I left for macOS.

What Is Yii?

Yii is an incredibly reliable, well-designed, high-performing framework for PHP, as Rails is for Ruby and similar to Laravel. If you’re wondering if you can build real-world applications in Yii, check out Meeting Planner and our Building Your Startup series.

  • How to Install Yii on Windows or a Mac

    How to Program With Yii2: Using the Advanced Application Template

    Let’s explore Yii’s advanced template, which provides integrated user sign-up and registration as well as a back-end website for administration features.
  • How to Install Yii on Windows or a Mac

    Building Your Startup With PHP: Table of Contents

    A guide to our ongoing series on launching your own business and product with PHP. Here’s what to expect in coming episodes. Check back regularly for updates.

I love coding in Yii. Everything is faster and easier for me. And it’s relatively straightforward as far as frameworks go (that’s me throwing shade at Rails).

We’ll start with the basics of what’s unique installing Yii in macOS, and then move on to Windows. As what’s needed to complete the installation on each platform converges, we’ll describe the remaining instructions in a unified form for both platforms.

Choosing Between Yii Basic and Yii Advanced

Yii Basic is the simplest form of Yii. You can build all kinds of applications with it, but it’s best for single tier, e.g. one customer facing side.

Here’s the directory structure of a Yii Basic application with just a set of directories for a single application:

  assets/             contains assets definition
  commands/           contains console commands (controllers)
  config/             contains application configurations
  controllers/        contains Web controller classes
  mail/               contains view files for e-mails
  models/             contains model classes
  runtime/            contains files generated during runtime
  tests/              contains various tests for the basic application
  vendor/             contains dependent 3rd-party packages
  views/              contains view files for the Web application
  web/                contains the entry script and Web resources

The Yii 2 Advanced Project Template is best for developing complex Web applications with multiple tiers, such as front end, back end, and console, each of which is a separate Yii application. For example, administrative sites can run in the back end, and cron tasks can run in the console environment.

In contrast, here is the directory structure for a Yii Advanced application with multiple tiers:

common
    config/              contains shared configurations
    mail/                contains view files for e-mails
    models/              contains model classes used in both backend and frontend
    tests/               contains tests for common classes    
console
    config/              contains console configurations
    controllers/         contains console controllers (commands)
    migrations/          contains database migrations
    models/              contains console-specific model classes
    runtime/             contains files generated during runtime
backend
    assets/              contains application assets such as JavaScript and CSS
    config/              contains backend configurations
    controllers/         contains Web controller classes
    models/              contains backend-specific model classes
    runtime/             contains files generated during runtime
    tests/               contains tests for backend application    
    views/               contains view files for the Web application
    web/                 contains the entry script and Web resources
frontend
    assets/              contains application assets such as JavaScript and CSS
    config/              contains frontend configurations
    controllers/         contains Web controller classes
    models/              contains frontend-specific model classes
    runtime/             contains files generated during runtime
    tests/               contains tests for frontend application
    views/               contains view files for the Web application
    web/                 contains the entry script and Web resources
    widgets/             contains frontend widgets
vendor/                  contains dependent 3rd-party packages
environments/            contains environment-based overrides

Each tier is its own site, but they can easily share code and a common database if desired. I use this template in our startup series. Yii Advanced also provides built-in configuration support for different environments, making team development easier.

Preparing macOS for Yii

I’ve been coding in Yii on macOS for several years now. Sure, there are lots of different ways to run an Apache, MySQL, PHP environment on a Mac, but I prefer MAMP.

Installing MAMP

How to Install Yii on Windows or a Mac

Basically, just visit the MAMP website and download the macOS package:

How to Install Yii on Windows or a Mac

Once downloaded, you can drag the package to the Applications folder and double-click to launch MAMP. This will display a MAMP window:

How to Install Yii on Windows or a Mac

Configuring MAMP

Click Preferences to configure the ports you want to the server on (I use 8888 for Apache):

How to Install Yii on Windows or a Mac

Click Web Server to review or change the directory of your server. I use Apache locally:

How to Install Yii on Windows or a Mac

Installing Composer on macOS

Yii2 requires Composer, a popular dependency manager for PHP. If you don’t already have Composer installed, do the following:

curl -s http://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

Then, use Composer to install Yii2. The installation request requires that you use your own GitHub account credentials; sign up if you don’t have an account.

As Rod describes further below, installing Yii requires the composer asset plugin:

composer global require "fxp/composer-asset-plugin:1.0.0-beta2"

He recommends setting up an account with GitHub and configuring an access token. The reason for this is that during the installation of Yii, the number of requests may exceed the GitHub API rate limit, and Composer may stop and ask for your GitHub login credentials to obtain a GitHub API access token during the installation. 

When ready, you can install Yii. We’ll use Yii basic and install it in the ~/sites/hello directory:

composer create-project --prefer-dist yiisoft/yii2-app-basic hello

Then, create a symlink for MAMP to your Sites app directory:

cd /Applications/MAMP/htdocs
ln -s ~/Sites/hello/ /Applications/MAMP/htdocs/hello

If you decide to install Yii Advanced, then it may help to activate and customize your virtual host file:

$ nano /Applications/MAMP/conf/apache/httpd.conf
 
# Virtual Hosts
Include /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf

Below, I’ve configured frontend.dev and backend.dev to map to a Yii Advanced install in the ~/sites/yiiplus directory which has a symbolic link in /Applications/MAMP.

$ nano /Applications/MAMP/conf/apache/extra/httpd-vhosts.conf
 
NameVirtualHost *:8888
 
<VirtualHost *:8888>
       ServerName frontend.dev
       DocumentRoot /Applications/MAMP/htdocs/yiiplus/frontend/web/
 
       <Directory "/Applications/MAMP/htdocs/yiiplus/frontend/web/">
           # use mod_rewrite for pretty URL support
           RewriteEngine on
           # If a directory or a file exists, use the request directly
           RewriteCond %{REQUEST_FILENAME} !-f
           RewriteCond %{REQUEST_FILENAME} !-d
           # Otherwise forward the request to index.php
           RewriteRule . index.php
 
           # use index.php as index file
           DirectoryIndex index.php
 
           # ...other settings...
       </Directory>
   </VirtualHost>
 
   <VirtualHost *:8888>
       ServerName backend.dev
       DocumentRoot /Applications/MAMP/htdocs/yiiplus/backend/web/
 
       <Directory "/Applications/MAMP/htdocs/yiiplus/backend/web/">
           # use mod_rewrite for pretty URL support
           RewriteEngine on
           # If a directory or a file exists, use the request directly
           RewriteCond %{REQUEST_FILENAME} !-f
           RewriteCond %{REQUEST_FILENAME} !-d
           # Otherwise forward the request to index.php
           RewriteRule . index.php
 
           # use index.php as index file
           DirectoryIndex index.php
 
           # ...other settings...
       </Directory>
   </VirtualHost>

If you decide to use Yii Advanced, I encourage you to also check out my tutorial on this which offers more details.

Those are the platform-specific steps for macOS. Now let’s look at preparing for Yii on Windows. Later, we’ll return to finish the configurations with steps that work for both platforms. If you’re strictly a macOS user, jump ahead to the Completing the Yii Configuration section.

Preparing Windows for Yii

For Yii on Windows, we’re going to use WAMP. To begin, you’ll need to download and configure WAMP on your Windows computer. For this tutorial, we will be installing WAMP on your local computer (which the server will address as localhost). If you wish to install on a production Windows server, you will need to contact your provider for server details and follow the recommendations for installing and configuring WAMP Server or an alternative Apache, MySQL, PHP stack for that environment.

Installing WAMP

How to Install Yii on Windows or a Mac

As the focus of this tutorial is on installing Yii, we suggest you consult one of the many excellent existing tutorials that cover installing WAMP; you will be surprised how easy it is. As it’s also a PHP application, the WordPress guide to installing WAMP is a good starting point.

Once we have installed and configured WAMP, we need to install Composer, which is a dependency manager and installer for PHP projects. This will enable us to get started with our Yii installation.

Installing Composer on Windows

Although you can download Yii packages from GitHub, in this tutorial we’re using Composer to install it. If you’re not familiar with Composer, you can learn more in this tutorial.

First let’s go to GitHub to download and install the latest version of Composer-setup.exe, which at this time is v4.5.0.

Once the install is complete, it is a good idea to log off and log on again to be sure all files are updated [Jeff here: or buy a Mac].

You can check your install by opening the Command prompt and going to:

cd Usersyour-username

Enter the following command:

composer -V

The version info for Composer should then be displayed, something like:

Composer version 1.4.1 2017-03-10 09:29:45

Install Composer Asset Plugin

In order to manage your project assets in the Composer .json, without having to install NPM or Bower, you will need to make sure Composer has all the packages it needs by running the install command for the Composer Assets plugin.

Open the command prompt on Windows and navigate to where your PHP folder is located. On this install, PHP is located in the directory wamp64bin and it is PHP version 7.0.10, so we type:

cd wamp64binphpphp7.0.10

Then type the following command:

composer global require "fxp/composer-asset-plugin:^1.3.1"

Keep in mind that software changes, so always be sure to check that you are working with the most current stable version. Be careful with betas because if you get too far out on the bleeding edge, things might start to break.

For the most current versions of Composer and Composer Asset Plugin:

Configuring WAMP for Your Yii Application

Now, let’s configure WAMP for Yii. Change your directory to the WAMP installationwww for this installation:

cd wamp64www

In this directory, we will create a new directory named Yii Basic by typing:

mkdir yii-basic

This is where we are going to install Yii Basic. You could skip this step and install Yii straight into the www directory, but creating a clearly named directory avoids confusion, especially if you plan to install both Yii Basic and Yii advanced templates.

In the new yii-basic directory, we run the following command to install the Yii Basic Template:

composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic yii-basic

We can verify Yii by navigating to the “Basic” folder in the directory you created:

cd wamp64binwww

Now we type in the command:

PHP yii serve

This will start up Yii using WAMP’s PHP engine.

Configuring the Host File in Windows

If you want to customize the local browser addresses for your site, or refer distinctly to the front end and back end of the Yii-Advanced site, you’ll need to do a bit more.

Either using the text editor’s Open File dropdown or by navigating directly in Windows Explorer, go to the file:

C:Windowssystem32driversetchosts

We are looking for the section that reads:

# localhost name resolution is handled within DNS itself.
127.0.0.1    localhost

In preparation for Yii-Advanced’s multiple sites, let’s add one for frontend and one for backend:

127.0.0.1 frontend.dev
127.0.0.1 backend.dev

It will look like this:

How to Install Yii on Windows or a Mac

You can find more on finding and setting up your Windows Host file here.

Enabling Virtual Hosts in the httpd.conf File

It is a good idea to check that Virtual Hosts are enabled in the Apache httpd.conf file.

Be very careful when editing the httpd.conf file—make a copy before you start, and be sure you understand what you are doing before you make edits, otherwise you can easily wreck your WAMP server. [Jeff here, sounds like Rod is speaking from experience.]

To find httpd.conf, type:

cd wamp64binapacheapache2.4.23conf

I like this guide for a more detailed explanation of editing of httpd.conf to enable functions relating to Virtual Hosts in Apache and configuring Virtual Hosts on WAMP.

Configure Virtual Hosts

We now need to configure our Apache Virtual Hosts. Using our text editor menu or Windows Explorer, we will navigate to the following directory:

C:Wamp64binapacheapache2.4.23confextrahttpd-vhosts.conf

There should already be a Virtual Host for localhost, so now we need to add Virtual Hosts for Yii frontend and Yii backend. I recommend that you type the name above each Virtual Host to avoid confusion. (Don’t forget to comment out the name!)

i.e. #Frontend

The Virtual Host config file should look something like this.

In this example, we installed Yii Advanced into c:/wamp64/www/yii-advanced and created an application named yii-application. It’s also okay to install Yii into www so your path could read more simply c:/wamp64/www/myapp/frontend/web.

How to Install Yii on Windows or a Mac

Pay close attention to the DocumentRoot and Directory lines. They must both contain the complete pathway to the Yii application directory all the way to the “web” file that is located within the frontend and backend directories respectively. The content of DocumentRoot and Directory is identical except that the path for Directory is contained in quotation marks.

Installing the Yii-Advanced Template for Windows

To install the Yii advanced template, let’s return to the wamp64www directory:

cd wamp64www

Now we will create a new directory named yii-advanced:

mkdir yii-advanced

In the new directory, we run the following command, which will install the Yii Advanced template:

composer create-project --prefer-dist yiisoft/yii2-app-advanced yii-application

How to Install Yii on Windows or a Mac

So far, the installation of Yii Basic and Yii Advanced has been the same. Now we will need to add a few more steps to get your Yii Advanced Template ready for action.

Completing the Yii Configuration

Steps for Both Windows and Mac

Creating the MySQL Database

Assuming PHPmyAdmin is installed on your WAMP server (it’s included with MAMP), you can actually create the database via the PHPmyAdmin GUI, but we are going to get hands on and use the SQL command line, which honestly does not take much more effort.

In the Windows command line, navigate to the MySQL folder by typing:

cd wamp64wwwbinmysqlmysql5.7.14bin

You can also do this from anywhere as long as WAMP or MAMP is in your local environment path.

Then, for both Mac and Windows, type:

mysql -u root -p

This will bring us to the mysql command line. Now we will execute the following command in SQL:

create database yii2test;

(You can name the database whatever you want, provided you make sure to use the appropriate name throughout the rest of the process.)

Now we will create a username and password for this database by typing the following SQL commands:

GRANT ALL ON yiit2est.* TO 'your-username'@'localhost' IDENTIFIED BY 'your_chosen_password’;
FLUSH PRIVILEGES;
EXIT;

You will now leave MySQL and be returned to the console command line.

Keep the database username and password on hand as we will need it to set up the PHP config file (common/config/main-local.php), which enables Yii to communicate safely with MySQL.

Initializing the Yii Advanced Application

This is unnecessary for Yii-basic installations.

To initialize Yii advanced, we will need to navigate to the Yii-Advanced application folder. In this case, that would be:

cd wamp64wwwyii-advanced

Then type init:

This will start the initialization script which will ask whether you wish to initialize Yii for a development or production environment; most likely it will look like this:

Which environment do you want the application to be initialized in?

[0] Development
[1] Production

For the purpose of this tutorial, we will be working in a development environment, so type in 0 and hit enter, and then type “yes” (without quotes) when prompted and the initialization will complete.

We are almost done—all that remains now are a few config steps, and you can get to work programming with Yii.

How to Install Yii on Windows or a Mac

Updating the Yii Configuration Settings

For Yii-basic, you’ll be editing /yii-basic/config/db.ini. For, Yii-advanced, you’ll be editing /yii-advanced/common/config/main-local.php.

In order to edit this file, we will need to use a text editor. Atom is a great choice that will serve you well as you get into more advanced coding.

To open the config file, either use the Open File dropdown in the text editor or navigate directly to the config file using Windows Explorer and right click Open With and select your text editor. (In Windows, you may need to run text editor as admin.)

The following example from the install we are using today illustrates this process. Keep in mind that you may be using a different drive designation and have a slightly different path depending on what you named your folders.

The config file should look something like this:

How to Install Yii on Windows or a Mac

Remember to enter the same username and password you used to set up your Yii MySQL database, otherwise Yii and MySQL will not play nice!

And please don’t even think about using your database’s root username and password in the config file! [Jeff here … really, don’t.]

Using the Yii Migration Tool

Yii Advanced has its own migrations. Now that MySQL is set up, we will need some tables. The Yii migrations create tables and schemas in your MySQL database programmatically.

To start the Yii Migration tool in Windows, we need to go to our Yii Installation directory by typing:

cd wamp64wwwyii-advancedyii-application

Again, you can choose to install it without the parent directory that Rod created for this demo. For example, for MAMP, I’m using:

$ cd ~/sites/yii-advanced

Now type the following command:

yii migrate

In a moment you will be asked if you want to "Apply the above migration?"

Type Yes and hit return. If all goes well, we will get a message that Yii migrated successfully.

How to Install Yii on Windows or a Mac

Visiting Your Yii Website

Now for the moment of truth. When you visit localhost:8888 in your browser, you should see:

How to Install Yii on Windows or a Mac

For Yii Advanced, you may need to try frontend.dev or include the frontend or backend site, e.g. localhost:8888/frontend. If you don’t enable your host file, you can access Yii directly via the path, localhost:8888/web.

If you installed the advanced template, go to the Signup link and input a username, the email address you wish to use, and a password.

Do not use your MySQL password (the one you entered into the PHP config file). This is the Yii user account database with new usernames and passwords.

Your first user registration will also be the Yii application’s administrative user with access to everything.

Now that you are signed up, type into the browser:

backend.dev

You should get an admin login screen where you can enter your new username and password:

How to Install Yii on Windows or a Mac

This will take you right back to the above Yii “Congratulations” page but as an authenticated user.

Now with all the congratulations going around, why not congratulate yourself as you have just successfully installed Yii. Nicely done. [Jeff here, if you did this on Windows, go buy a Mac and try it on there.]

In Closing

I hope our tutorial today helps you get started with Yii. Rod and I enjoyed writing this together.

Watch for upcoming tutorials in our Programming with Yii2 series as we continue diving into different aspects of the framework. Be sure to check out our Building Your Startup With PHP series which is using Yii2’s advanced template as we build a real-world application.

How to Program With Yii’s Getting Started episode does a great job of going into detail about setting up Yii basic and a production Linux server.

If you’d like to know when the next Yii2 tutorial arrives, follow me @reifman on Twitter or check my instructor page. My instructor page will include all the articles from this series as soon as they are published.

Related Links