Run a php file inside Yii2

Hello,
Inside my website I need to run some tasks each day, my plan is put all that instructions in one PHP file and run it using a cron job.

But I want to use Yii2 environment for that script because it need to use the DB operations and some libs from Yii2.

is that possible? Can you give me some ideas about how to start?

Thanks!

Mario

Hi Mario, yes it is possible.

I’d recommend you to use the advanced template: https://github.com/yiisoft/yii2-app-advanced

With this template you can configure routes for console using the same log for web. More info in the Yii2 docs: https://www.yiiframework.com/doc/guide/2.0/en/tutorial-console

Thanks! I’ll check that link!

For this type of problem I write a command line controller. Public methods are available as ./yii commands.

I use the basic template https://github.com/yiisoft/yii2-app-basic.

Here is some sample code. Put the file in the commands folder as MailController.php.

<?php
namespace app\commands;

use Yii;
use yii\console\Controller;
use app\models\Mail;
use ZBateson\MailMimeParser\MailMimeParser;

class MailController extends Controller
{
	/*
	 * Usage: ./yii mail/get-new
	 */
	public function actionGetNew()
	{
		$imap_driver = new \imapDriver();

		// [...] Do stuff	

		// Process messages by calling a private function
		foreach ($ids as $id) {
			$mail = $imap_driver->get_mail_from_uid($id);
			if (!$mail) {
				echo 'get_mail_from_uid(' . $id . ') failed: ' . $imap_driver->error . "\n";

				return false;
			}
			$this->processMail($mail);
		}

	}

	/*
	 * This method is private and cannot be invoked from the command line
	 */
	private function processMail($mail)
	{
		$in_console = (getenv('TERM') != '');

		$mailParser = new MailMimeParser();
		$message = $mailParser->parse($mail);

		// [...] Do stuff	
	}
}

These bits must match for the ./yii command to be available.

CleanShot 2021-04-16 at 10.56.59

Perfect! thanks! @clescuyer and @bpanatta

I think you have an error in your code, you first line

namespace app\commands;

need to be replaced with:


namespace console\controllers;

Why? Works for me.

Give me a namespace error when I launch it from console…
With my code works fine.

1 Like