PHP built-in server integration

I was playing around with another PHP framework which I didn't really liked anyway but it had simple and nice integration for PHP built in web server so I decided to write one for Yii (since this is my primary PHP framework)

More info about PHP's web server.

What you need to do:

  1. Create file named "ServeController.php" under "commands" folder in Yii application root directory.
  2. Paste code which you can find below and save file.

Usage

You can start default web server by running command:

yii serve

This will create web server which you can access by visiting http://localhost:8080

You can pass web root location, hostname and port parameters.

Web root is a path relative to Yii application root directory ("web" is default), so running:

yii serve frontend

will set root directory to "Your/path/to/yii/frontend", i.e. "C:/xampp/htdocs/myYiiApp/frontend/"

You can point web root to php file which can emulate Apache mod_rewrite.

More information about this can be found in PHP manual

Content of ServeController.php

<?php
namespace app\commands;

use yii\console\Controller;

/**
 * This command runs PHP built in web server
 *
 * @author Headshaker
 */
class ServeController extends Controller
{
    /**
     * This command echoes what you have entered as the message.
     * @param string $root web root location relative to Yii app root.
     * @param string $host hostname of the server.
     * @param string $port port to listen for connections.
     */
    public function actionIndex($root = "web", $host="localhost", $port= 8080)
    {
        $basePath = \Yii::$app->basePath;

        $webRoot = $basePath.DIRECTORY_SEPARATOR.$root;

        echo "Yii dev server started on http://{$host}:{$port}/\n";
        echo "Document root is \"{$webRoot}\"\n";

        passthru('"'.PHP_BINARY.'"'." -S {$host}:{$port} -t \"{$webRoot}\"")."\n";
    }
}