USA

2. Define a Sharable Model & Migration

Instead of relying on pre-existing database tables, use migrations for portability.

Create Migration for post Table

Run:

bash
php yii migrate/create create_post_table

Then, edit migrations/mXXXX_create_post_table.php:

php
use yii\db\Migration;

class mXXXX_create_post_table extends Migration
{
public function safeUp()
{
$this->createTable('post', [
'id' => $this->primaryKey(),
'title' => $this->string()->notNull(),
'content' => $this->text()->notNull(),
'created_at' => $this->timestamp()->defaultExpression('CURRENT_TIMESTAMP'),
]);
}

public function safeDown()
{
$this->dropTable('post');
}
}

Run the migration:

bash
php yii migrate

Generate the Model

bash
php yii gii/model --tableName=post --modelClass=Post

3. Setup Controller and Views

Create Controller

controllers/PostController.php

php
namespace app\controllers;

use app\models\Post;
use yii\web\Controller;
use yii\web\NotFoundHttpException;

class PostController extends Controller
{
public function actionIndex()
{
$posts = Post::find()->all();
return $this->render('index', compact('posts'));
}

public function actionView($id)
{
return $this->render('view', ['post' => $this->findModel($id)]);
}

protected function findModel($id)
{
if (($model = Post::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested post does not exist.');
}
}

Create Views

  • views/post/index.php
php
<?php foreach ($posts as $post): ?>
<h2><a href="<?= \yii\helpers\Url::to(['post/view', 'id' => $post->id]) ?>"><?= $post->title ?></a></h2>
<p><?= $post->content ?></p>
<?php endforeach; ?>
  • views/post/view.php
php
<h1><?= $post->title ?></h1>
<p><?= $post->content ?></p>

4. Share the Application

Package it for Sharing

  1. Exclude Unnecessary Files: Add a .gitignore file:
    bash
    /vendor/
    /runtime/
    /web/assets/
  2. Include composer.lock to lock dependencies.
  3. Ensure Migrations Exist (migrations/ folder).

Sharing Methods

  • Git Repository: Push to a Git repo.
  • Zip Archive: Compress & distribute.
  • Dockerize: Create a docker-compose.yml for MariaDB.

5. Install on Another Machine

To deploy:

bash
git clone <repo_url> yii2-sharable
cd yii2-sharable
composer install
php yii migrate
php yii serve

Visit: http://localhost:8080/index.php?r=post

Now you have a sharable Yii2 app with MariaDB, a basic model, and migrations for easy deployment!

Mr. Arch Brooks, Software Engineer, Brooks Computing Systems, LLC authored this article.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.


Page dynamically generated on

Brooks Computing Systems, LLC
Quality, Reliability & Service