How to call a console command in web application action in Yii? - yii

I have a console command to do a consumer time, AND I need to know how to call (execute) it in a web application action in YII.
class MyCommand extends CConsoleCommand{
public function actionIndex(){
$model = new Product();
$model->title = 'my product';
...
$model->save();
.
.
.
}
}
I want to execute this code.

try this:
Yii::import('application.commands.*');
$command = new MyCommand("test", "test");
$command->run(null);
The 2 parameters with value "test" must be set but do not have an impact, they are used for the --help option when using the console.
/**
* Constructor.
* #param string $name name of the command
* #param CConsoleCommandRunner $runner the command runner
*/
public function __construct($name,$runner)
{
$this->_name=$name;
$this->_runner=$runner;
$this->attachBehaviors($this->behaviors());
}
https://github.com/yiisoft/yii/blob/master/framework/console/CConsoleCommand.php#L65

Try this
Yii::import('application.commands.*');
$command = new GearmanCommand('start', Yii::app()->commandRunner);
$command->run(array('start', '--daemonize', '--initd'));
where array('start', '--daemonize', '--initd') is a action and action parameters

I had same problem - i need to call action from inside controller and from command
I said same problem because it actually same - you have action which you need to call from console, and call it from controller too.
If you need to call an action(command) as a part of controller action, then i think you need to modify this solution a little. Or is my solution is enough for you?
So here is my solution:
first create action as said in http://www.yiichina.net/doc/guide/1.1/en/basics.controller#action
class NotifyUnsharedItemsAction extends CAction
{
public function run()
{
echo "ok";
}
}
then in controller action is loaded as usuall:
class TestController extends Controller
{
public function actions() {
return array(
'notifyUnsharedItems'=>'application.controllers.actions.NotifyUnsharedItemsAction',
);
}
and in command i run action in such way:
class NotifyUnsharedItemsCommand extends CConsoleCommand
{
public function run($args)
{
$action = Yii::createComponent('application.controllers.actions.NotifyUnsharedItemsAction',$this,'notify');
$action->run();
}
}

Accepting that we are on linux server, for Yii 1.1 real life example would be:
$run = '/usr/bin/php ' . Yii::getPathOfAlias('root').'/yiic' [command]
exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $run, '/dev/null', '/dev/null'));
This will run Yii console command in the background.

Yii is PHP -> you can use the standard php constructs specified at http://php.net/manual/en/function.exec.php and the related methods near the bottom of the page, depending on what exactly you want to achieve.

Also, another very clean solution from cebe on gist:
<?php
// ...
$runner=new CConsoleCommandRunner();
$runner->commands=array(
'commandName' => array(
'class' => 'application.commands.myCommand',
),
);
ob_start();
$runner->run(array(
'yiic',
'idbrights',
));
echo nl2br(htmlentities(ob_get_clean(), null, Yii::app()->charset));
Yii::app()->end();

Typically what you should do in these situations is refactor.
Move the "common" code out of the MyCommand and place it into a class located in the components folder.
Now you can place any head on top of the "common" code without altering your functionality. For example:
protected/components/Mywork.php:
<?php
class Mywork
{
public function doWork()
{
$model = new Product();
$model->title = 'my product';
...
$model->save();
...
}
}
protected/controller/MyworkController.php:
<?php
class MyworkController
{
public function actionDowork()
{
$mywork = new Mywork;
...
}
}
protected/commands/MyworkCommand.php:
<?php
class MyworkCommand extends CConsoleCommand
{
public function run($args)
{
$mywork = new Mywork;
...
}
}
This approach makes testing easier too as you can test Mywork as a single unit outside of the view you are using.

Related

Ho to call variables items on Joomla Component

I'm trying to create my first component in Joomla but I can't understand how it works really :D
I create a basic component with "Component Creator". (I saved a lot of time...).
Now, I have a table in my DB where I've put my data:
id = 1
name = Andrea
note = Ciao
Now, I want to call it from the page using Joomla Language.
On my models/component.php i wrote:
class Variabili extends JModelLegacy
{
function estraivariabili()
{
$db =& JFactory::getDBO();
$db->setQuery("SELECT * FROM #__table")->loadObjectList();
return $value;
}
}
and on my default.php I wrote
$model=$this->Variabili();
//call the method
$items=$model->estraivariabili();
//print
print_r($items);
But on the page I have this error:
0 Call to undefined method Calcolo_imposteViewCalcoloonline::Variabili()
Where is a mistake?
Please be gentle with me because I'm a beginner: D
Thanks in advance
Andrea
You have committed a few wrongs. I've rewritten your functions so that you can get it. Let's have a look-
The model, it looks almost okay. Just change it like-
class Variabili extends JModelLegacy
{
// Make the function public
public function estraivariabili()
{
$db = &JFactory::getDBO();
// Put the result into a variable first, then return it.
$value = $db->setQuery("SELECT * FROM #__table")->loadObjectList();
return $value;
}
}
And now call the model functions not from default.php, rather than write your code inside view.html.php file.
Inside the display function of view.html.php file first, get the model instance by using getModel() function.
$model = $this->getModel();
Now you can get the items by using this $model class instance.
$this->items = $model->estraivariabili();
This will bring you the data from the database table. And you can use the data at default.php file.
Just try at default.php file-
print_r($this->items);

Respect\Validation custom Rule with PDO?

I am learning Slim Framework v4 and decided to use Respect\Validation to validate inputted data and have hit a snag where I do not know how to inject the PDO into my custom rule I created.
The idea is to validate some inputs against the database if the provided data exist (or in another instances, if it was inputted correctly). In this specific case, I am tying to validate user's credentials for log in. My idea is this:
AuthController.php:
v::with('app\\Validators\\');
$userValidation = v::notBlank()->email()->length(null, 255)->EmailExists()->setName('email');
EmailExists() is my custom rule.
EmailExists.php:
namespace app\Validators;
use PDO;
use Respect\Validation\Rules\AbstractRule;
class EmailExists extends AbstractRule
{
protected $pdo;
public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
}
public function validate($input, $id = null)
{
// a PDO query that checks if the email exists in database
}
}
But I get an error of Too few arguments to function app\Validators\EmailExists::__construct(), 0 passed and exactly 1 expected, which is somewhat expected since the AbstractRule does not have a PDO injected and my class extends it.
So how to inject the PDO interface so that I can use it in my custom rules?
Are you guys using another approach in validating this kind of data? Do note that I am writing an API, so the database validation is somewhat a must and after Googling for past two days, I have no solutions at hand.
I am also using a PHP-DI where I create PDO interface. This is my dependencies.php file:
declare(strict_types=1);
use DI\ContainerBuilder;
use Psr\Container\ContainerInterface;
use app\Handlers\SessionMiddleware;
return function (ContainerBuilder $containerBuilder) {
$containerBuilder->addDefinitions([
PDO::class => function (ContainerInterface $c) {
$settings = $c->get('settings')['db'];
$db = new PDO("mysql:host={$settings['host']};dbname={$settings['database']};charset={$settings['charset']},{$settings['username']},{$settings['password']}");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::MYSQL_ATTR_INIT_COMMAND, "SET NAMES 'utf8',time_zone='{$offset}'");
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
return $db;
},
'session' => function(ContainerInterface $c) {
return new SessionMiddleware;
}
]);
};
And (part of) index.php:
declare(strict_types=1);
use DI\ContainerBuilder;
use Slim\Factory\AppFactory;
// Instantiate PHP-DI ContainerBuilder
$containerBuilder = new ContainerBuilder();
// Set up settings
$settings = require __DIR__ . '/../app/settings.php';
$settings($containerBuilder);
// Set up dependencies
$dependencies = require __DIR__ . '/../app/dependencies.php';
$dependencies($containerBuilder);
// Build PHP-DI Container instance
$container = $containerBuilder->build();
// Instantiate the app
AppFactory::setContainer($container);
$app = AppFactory::create();
// Register middleware
$middleware = require __DIR__ . '/../app/middleware.php';
$middleware($app);
// Register routes
$routes = require __DIR__ . '/../app/routes.php';
$routes($app);
// Add Routing Middleware
$app->addRoutingMiddleware();
// Run App & Emit Response
$response = $app->handle($request);
$responseEmitter = new ResponseEmitter();
$responseEmitter->emit($response);
Any help would be appreciated.
Use your user model to count the number of rows in the user table where there is a hit.
If it is not exactly 0, the check returns false, if it is exactly 0, the check passes.
So you don't have to include a PDO at this point. I use Slim 3 and that works quite well.
namespace app\Validators;
use Respect\Validation\Rules\AbstractRule;
class EmailAvailable extends AbstractRule {
/**
* #param $input
*
* #return bool
*/
public function validate ($sInput) {
return User::where('user_email', $sInput)->count() === 0;
}
}
class EmailAvailable extends AbstractRule {
/**
* #param $input
*
* #return bool
*/
public function validate ($sInput) {
return User::where('user_email', $sInput)->count() === 0;
}
}

symfony 4 Upload

How to upload a file in symfony 4.I have done with the symfony document. I don't know where I have missed something. Its throws error while uploading file give me some clues
REFERED LINK:
https://symfony.com/doc/current/controller/upload_file.html
ERROR:
The file "" does not exist
Entity
public function getBrochure()
{
return $this->brochure;
}
public function setBrochure($brochure)
{
$this->brochure = $brochure;
return $this;
}
File upload Listener
class FileUploader
{
private $targetDirectory;
public function __construct($targetDirectory)
{
$this->targetDirectory = $targetDirectory;
}
public function upload(UploadedFile $file)
{
$fileName = md5(uniqid()).'.'.$file->guessExtension();
$file->move($this->getTargetDirectory(), $fileName);
return $fileName;
}
public function getTargetDirectory()
{
return $this->targetDirectory;
}
}
This Symfony tutorial works fine for me so I'll try to explain how and perhaps it will help you or people still looking for an answer, this post getting a bit old.
So first you have to create the FileUploader service in App\Service for better reusability (chapter: Creating an Uploader Service). You can basically copy/paste what they've done here, it works like a charm. Then you need to open your services.yaml in Config folder and explicit your brochure directory:
parameters:
brochures_directory: '%kernel.project_dir%/public/uploads/brochures'
# ...
services:
# ...
App\Service\FileUploader:
arguments:
$targetDirectory: '%brochures_directory%'
Now everything is normally ready to use your FileUploader service.
So if you're in your controller (for example), I guess you want to use it in a form. Thus, you just have to do this (don't forget to use your Service in your Controller):
public function myController(FileUploader $fileUploader)
{
// Create your form and handle it
if ($form isValid() && &form isSubmitted()) {
$file = $myEntity->getBrochure();
$fileName = $this->fileUploader->upload($file);
$myEntity->setBrochure($fileName);
// Form validation and redirection
}
// Render your template
}
One important point I forgot to say. In your FormType, you need to say that the Brochure will be a FileType:
$builder->add('brochure', FileType::class)
But in your entity you have to specify your brochure is stored as a "string":
/**
* #MongoDB\Field(type="string")
*/
protected $brochure;
The reason is your file is getting uploaded and saved in your public/uploads/brochure. But your database is only remembering a string path to reach it.
I hope this will help!

Error: Laravel Notifications Broadcast Exception

I am trying to build a real-time notification system in an app I am working on. one of the requirements is, when an ID is expired, that particular user should be sent a notification. Since this task needs to be run on daily basis at the maximum, I developed an artisan command that is easy to run with CRON jobs i.e. Laravel Scheduler. Every thing is working fine i.e. the artisan command is run and notification is generated & stored in database & all the related stuff. but each time a notification is generated, the page needs to be reload and this is where I am stuck. I am trying to make it happen in real time but a very strange error is being thrown & I don't know what it means.
Here is the necessary code:
Artisan.file
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\User;
use Carbon\Carbon;
use App\Notifications\UserIdExpired;
class UpdateCatalog extends Command
{
/**
* The name and signature of the console command.
*
* #var string
*/
protected $signature = 'check:expiry';
/**
* The console command description.
*
* #var string
*/
protected $description = 'dummy command to check its purpose';
/**
* Create a new command instance.
*
* #return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$ZERO = 0;
$MONTH = 30;
$today = Carbon::today();
$users = User::all();
foreach($users as $user){
$today = Carbon::today();
$expiryDate = $user->qidexpire_on;
if($today->diffInDays($expiryDate, false) <= $MONTH && $today->diffInDays($expiryDate, false) >= $ZERO){
$this->info($user);
$this->info($expiryDate->diffInDays($today));
$user->notify(new UserIdExpired);
} else {
}
}
}
}
}
Notification.file
<?php
namespace App\Notifications;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Messages\BroadcastMessage;
class UserIdExpired extends Notification
{
use Queueable;
public function via($notifiable)
{
return ['database', 'broadcast'];
}
public function toDatabase($notifiable)
{
return [
'user' => $notifiable,
'id_expired' => Carbon::now()
];
}
public function toBroadcast($notifiable)
{
return new BroadcastMessage([
'user' => $notifiable,
'id_expired' => Carbon::now()
]);
}
}
when I run php artisan check:expiry from console, Notification is generated & on page reload it updates number of notifications but its not happening in real time. Following is the error that is shown on console
[Illuminate\Broadcasting\BroadcastException]
Note: Whenever i reload the page, Pusher Console shows the respective log like connected private channel and host & all that stuff which means the problem is not on the client side, (yet)
just found the answer on this issue
had to encrypt false since I am developing locally

CakePHP 3 integeration test without a model/entity

I'm trying to test a controller function...
I want to test a couple of things:
A) That it throws an invalid request exception when a certain argument is used
B) That it works correctly when the correct argument is made.
I've written some unit tests and those all seem cool. The only documentation I can find on this is http://book.cakephp.org/3.0/en/development/testing.html but the integration testing, whilst interesting and potentially useful, I can't seem to get how I am suppose to be implement it without using fixtures (which I don't want to do necessarily).
namespace App\Test\TestCase\Controller;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\IntegrationTestCase;
class MusterControllerTest extends IntegrationTestCase
{
public function testIn()
{
$this->in();
$this->setExpectedException('Invalid request');
}
}
class MusterController extends AppController {
public $helpers = array('Address');
public function beforeFilter(Event $event) {
$this->Auth->allow('in');
$this->layout = 'blank';
$this->autoRender = false;
$this->loadComponent('Rule');
parent::beforeFilter($event);
}
public function in($param = null){
if (!$this->request->is(array('post', 'put')) || $this->request->data('proc')!='yada' || is_null($param)){
throw new NotFoundException(__('Invalid request'));
}
$this->processRequest($this->request->data('hit'), $this->request->data('proc'), $param);
}
Pointers appreciated.
The IntegrationTestCase class, as its name implies, is meant for integration testing. That is, it will be testing the interaction between the controller and any other class it uses for rendering a response.
There is another way of testing controller, which is more difficult to accomplish, but allows you to test controller methods in isolation:
public function testMyControllerMethod()
{
$request = $this->getMock('Cake\Network\Request');
$response = $this->getMock('Cake\Network\Response');
$controller = new MyController($request, $response);
$controller->startupProcess();
// Add some assertions and expectations here
// For example you could assing $controller->TableName to a mock class
// Call the method you want to test
$controller->myMethod('param1', 'param2');
}