Yii - How to access to model and call action in yiic - yii

I have an action that prints "Hello World":
public function actionStart()
{
echo 'Hello World';
}
I will to run a cron job that calls this action every minute.
How I can do this with yiic ?
UPDATE:
I create console app. I have cron.php inside index.php:
<?php
defined('YII_DEBUG') or define('YII_DEBUG',true);
// including Yii
require_once('framework/yii.php');
// we'll use a separate config file
$configFile='protected/config/c.php';
// creating and running console application
Yii::createConsoleApplication($configFile)->run();
and config/c.php:
<?php
return array(
// This path may be different. You can probably get it from `config/main.php`.
'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name'=>'Cron',
'preload'=>array('log'),
'import'=>array(
'application.models.*',
'application.components.*',
),
// We'll log cron messages to the separate files
'components'=>array(
'log'=>array(
'class'=>'CLogRouter',
'routes'=>array(
array(
'class'=>'CFileLogRoute',
'logFile'=>'cron.log',
'levels'=>'error, warning',
),
array(
'class'=>'CFileLogRoute',
'logFile'=>'cron_trace.log',
'levels'=>'trace',
),
),
),
// Your DB connection
'db'=>array(
'class'=>'CDbConnection',
// …
),
),
);
and protected/commands/MyCommand.php:
<?php
class MyCommand extends CConsoleCommand
{
public function run($args)
{
$logs = Log::model()->findAll();
print_r($logs);
die();
}
}
when I run this:
$ ./protected/yiic my
I got this error:
PHP Error[2]: include(Log.php): failed to open stream: No such file or directory
in file /path/to/app/folder/framework/YiiBase.php at line 427
#0 /path/to/app/folder/framework/YiiBase.php(427): autoload()
#1 unknown(0): autoload()
#2 /path/to/app/folder/protected/commands/MyCommand.php(6): spl_autoload_call()
#3 /path/to/app/folder/framework/console/CConsoleCommandRunner.php(71): MyCommand->run()
#4 /path/to/app/folder/framework/console/CConsoleApplication.php(92): CConsoleCommandRunner->run()
#5 /path/to/app/folder/framework/base/CApplication.php(180): CConsoleApplication->processRequest()
#6 /path/to/app/folder/framework/yiic.php(33): CConsoleApplication->run()
#7 /path/to/app/folder/protected/yiic.php(7): require_once()
#8 /path/to/app/folder/protected/yiic(3): require_once()
How I can fix this?

First you have to create a command: http://www.yiiframework.com/doc/guide/1.1/en/topics.console#creating-commands
Then you can acess your function by running this command:
yiic yourCommand start

You have to load your models in Console application.
Open console.php configuration file, and add this line under the line 'name'=>'My Console Application',
'import'=>array(
'application.models.*'
),
It should work.

It seems that your don't have such 'log.php' file you are including.
maybe try this from console :
touch /path/to/app/folder/protected/log.php
You should have another error message then (or it will run smoothly).

Just open your yiic.php file check framework path in it.

Related

Web push notification example with PHP backend

I am looking for an example for web push notification with JS code and PHP backend. Can anyone share example code or a tutorial?
Here's a basic example that uses web-push-php : https://github.com/Minishlink/web-push-php-example
Main PHP code is:
<?php
require __DIR__ . '/vendor/autoload.php';
use Minishlink\WebPush\WebPush;
$auth = array(
'VAPID' => array(
'subject' => 'https://github.com/Minishlink/web-push-php-example/',
'publicKey' => 'BCmti7ScwxxVAlB7WAyxoOXtV7J8vVCXwEDIFXjKvD-ma-yJx_eHJLdADyyzzTKRGb395bSAtxlh4wuDycO3Ih4',
'privateKey' => 'HJweeF64L35gw5YLECa-K7hwp3LLfcKtpdRNK8C_fPQ', // in the real world, this would be in a secret file
),
);
$webPush = new WebPush($auth);
$res = $webPush->sendNotification(
$subscription['endpoint'],
"Hello!", // payload
$subscription['key'],
$subscription['token'],
true // flush
);
// handle eventual errors here, and remove the subscription from your server if it is expired
Hope this helps :)

can't test eloquent with php unit

I try to implement some unit tests with phpUnit, on a project that uses Eloquent. The installation is made with composer for both frameworks. But when I try to implement a simple example test, it fails loading database.php
the example test
include("database.php");
class ArticleControllerTest extends TestCase
{
public function testAccueil()
{
//récupère la date du jour
$a = \app\model\Article::first();
$this->assertInternalType("string", $a->titreGeneral);
}
}
Database.php
<?php
require 'vendor/autoload.php';
use Illuminate\Container\Container;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Events\Dispatcher;
$capsule = new Capsule;
$capsule->addConnection(array(
'driver' => 'mysql',
'host' => 'localhost',
'database' => 'spectacles',
'username' => 'root',
'password' => 'root',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => ''
));
$capsule->setEventDispatcher(new Dispatcher(new Container));
$capsule->setAsGlobal();
$capsule->bootEloquent();
error message with these script (the database is in the right folder)
PHP Warning: include(../../database.php): failed to open stream: No such file or directory in /Applications/MAMP/htdocs/spectacles/TestUnits/controllerTest/ArticleControllerTest.php on line 6
Warning: include(../../database.php): failed to open stream: No such file or directory in /Applications/MAMP/htdocs/spectacles/TestUnits/controllerTest/ArticleControllerTest.php on line 6
PHP Warning: include(): Failed opening '../../database.php' for inclusion (include_path='.:') in /Applications/MAMP/htdocs/spectacles/TestUnits/controllerTest/ArticleControllerTest.php on line 6
Warning: include(): Failed opening '../../database.php' for inclusion (include_path='.:') in /Applications/MAMP/htdocs/spectacles/TestUnits/controllerTest/ArticleControllerTest.php on line 6
And error messages when I try to put the code in database.php directly in the example test :
PDOException: SQLSTATE[HY000] [2002] No such file or directory
I don't think the problem comes prom the paths (they are the right paths). Did I miss something ?
PDOException: SQLSTATE[HY000] [2002] No such file or directory means the database could not connect.
The other errors are clearly telling you that the script could not include the database.php file.
The paths are not correct. You are not properly understanding how include() works. Read http://php.net/manual/en/function.include.php.
In a nutshell, the following code expects the database.php file to exist in the same directory as the file itself, or on the include path.
include("database.php");
class ArticleControllerTest extends TestCase
{
...
These may also help:
Understanding include_path output PHP
Include Config and Database from other files

How hide PDOException with zend framework 2 on production environment?

We use a zend framework 2 for a web application.
We though to have disabled error_reporting and display_errors in our production environment.
But if an SQL error occured (It should not in production but ... :-) ), the exception is still displayed:
PDOException
File:
[...]/vendor/doctrine/dbal/lib/Doctrine/DBAL/Statement.php:165
Message:
SQLSTATE[42000]: Syntax error or access violation
The query use Doctrine\DBAL\Statement (Doctrine2).
We cannot find where to globally catch this exception.
Ensure you have the correct view_manager config settings.
// config/autoload/global.php
return array(
'view_manager' => array(
'display_not_found_reason' => false,
'display_exceptions' => false,
),
);
Remember that this config is merged; if it's in your main global.php it will take preference over the module.config.php.
How it works
Every time ZF2 encounters and error (an exception) it will always catch the error. Instead of 'rethrowing' the exception information to the screen, the info is added to the MVC event and an 'error' event is triggered (either dispatch.error or render.error depending on where it is within the dispatch loop).
The Zend\Mvc\View\Http\ViewManager attaches 'error listeners' to handle these occurrences - (normally to show the error template). If you're using the standard skeleton application, the default error template will check the display_exceptions option and only render the error if it's enabled.
inside: Zend\Db\Adapter\Driver\Pdo\Connection
search for line :
$this->resource = new \PDO($dsn, $username, $password, $options);
$this->resource->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);
and change it into:
$this->resource = new \PDO($dsn, $username, $password, $options);
$this->resource->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_SILENT);
I don't know if there is a way to override it globally without changing it in the library itself..
this is how i do it, inside index.php
try {
include ROOT . '/init_autoloader.php';
Zend\Mvc\Application::init(include 'config/application.config.php')->run();
} catch (Exception $e) {
if (IS_DEVELOPMENT_SERVER)
throw $e;
else {
echo('Error : ' . $e->getCode() . " " . $e->getMessage());
}
}

git ignore Yii database details

Some of the details in the main.php needed by all application instances (URL details) and some details will be specific to each application instance (database details).
Is there any idea to separate the database details from protected/config/main.php?
Just include the shared configuration from another PHP file:
main.php:
return array
(
....
'components' => array
(
'db' => include('sharedDatabaseConfiguration.php');
)
);
sharedDatabaseConfiguration.php:
return array('host' => ...);
You might have to add a path or something, depending where the file is stored.
Edit: Btw, Yii also has a fancy CMap::mergeArray() function that can do something similar (in case you want to "augment" the contents of a single config file with that from another one. Look at the default generated console.php for an example of that.
You can find an idea here: Manage application configuration in different modes .
Basically it works by importing a different PHP file (your db configuration) and merging the includedarrays:
<?php
return CMap::mergeArray(
require(dirname(__FILE__).'/db-config.php'),
array(
'basePath' => dirname(__FILE__).DIRECTORY_SEPARATOR.'..',
'name' => 'Page Title',
...
)
);
?>
You can use separate configuration file (e.g. protected/config/production.php), that is based on your main configuration file and that overrides some settings using CMap::mergeArray as this answer suggests:
return CMap::mergeArray(
require(dirname(__FILE__) . '/main.php'),
array(
'components' => array(
'db' => array(
'connectionString' => '...',
'username' => '...',
'password' => '...',
),
),
)
);
Then you can add protected/config/production.php to .gitignore.

Bigcommerce Class 'Bigcommerce\Api\Error' not found

I keep getting this error when I try to execute a simple script on the server while it runs fine on my local machine.
Error
Fatal error: Class 'Bigcommerce\Api\Error' not found in
/customers/0/4/1/myDomainName/httpd.www/demo/hello/bigcommerce.php on
line 370
link to API
Sample Code
require_once 'bigcommerce.php';
use Bigcommerce\Api\Client as Bigcommerce;
Bigcommerce::configure(array(
'store_url' => 'https://www.mystore.com/',
'username' => 'myUsername',
'api_key' => 'myPass'
));
Bigcommerce::setCipher('RC4-SHA');
Bigcommerce::verifyPeer(false);
?>
Php Version
Server: 5.3.23
Local: 5.3.13
I fixed it by moving the declaration of class Error to just above the line 370 where class ClientError was declared.