How to process multiple task in codeigniter cli at the same time - php

I am not sure if this is doable or not. I am running cron job to process data and they are all independent of each other.
For example i have a data [x,y,z] and i have a method in the parent controller that does what it needs to do. Process takes little long and hence my queue is piling up since it is doing one at a time. I tried forking process but it loses connection to the mongo database. Therefore, I had to remove fork for now but please let me know if i can reconnect.
Pseudocode
MyTools.php
class MY_Tools extends CI_Controller {
...
public function process($item) {
Make curl request
Update database for the item
}
}
Tools.php
class Tools extends MY_Tools {
...
public function getAllDate() {
$data = fetchDataFromDB() => [X,Y,Z]
$i = 0
while ($i < sizeof($data) {
$this->process($data[$i]);
$i++;
}
}
}
if i can do this without waiting for another process to complete and just keep on going, that will be great
In addition, I am using php7
cimongo library for codeigniter and https://github.com/alcaeus/mongo-php-adapter
Possible Solution
For php7, i have used this for gearman installation
https://techearl.com/php/installing-gearman-module-for-php7-on-ubuntu
Codeigniter gearman library that I used : https://github.com/appleboy/CodeIgniter-Gearman-Library
To overcome static method accessing parent controller, use singleton method
I was struggling with this for a bit and hopefully it will help someone
Example
class MY_Tools extends CI_Controller {
private static $instance;
function __construct() {
parent::__construct();
self::$instance =& $this;
}
public static function get_instance()
{
return self::$instance;
}
}
To Access
MY_Tools::get_instance()->YOUR_PUBLIC_METHODS();
Hope this can help someone

Related

Magic behind loading model in codeigniter

Guys before few days I went for interview,and interviewer asked me a question,which is still only question and I could not find its answer.
To Load a Model In Codeigniter
we do,
$this->load->model('xyz_model');
then magically
$this->xyz_model->function_of_xyz_model();
Above line lets us access function of 'xyz_model'
named'function_of_xyz_model'
How it all happen,which game is played under the carpet to do all above.
As I'm not well experienced in OPP so please point out the concepts(if any) used inside.
I imagine something like this (although it`s very robust and many validations should be done beforehand), magic methods are the key :
class ControllerOrSimilar {
/**
* Loader
*/
var $loader;
public function __get($instance) {
//retrieve static instances loaded in class Loader
return Loader::$instances[$instance];
}
}
class Loader {
static $instances = array();
public function load($modelRequested) { //instanciate in static variables to be accessed globally
if(!$this->$instances[$modelRequested]) {
$this->$instances[$modelRequested] = new $modelRequested();
}
}
}
Although the actual implementation I think it`s different, I have worked with codeigniter but never gone in the depts of the implementation

How to use threading in Laravel to run stored procedures

I want to use php threads for asynchronously loading a function that executes a mysql stored procedure. The stored procedure takes a lot of time to load, so keeping it asynchronous is the only optimal solution, I found.
I have no idea on how to bring the threading inside Laravel. Laravel has queues but I want to do it directly in script with thread.
What i've done to approach a similar issue (I've done it in a sync command) is to create a class that extends from Thread and call it from the laravel code.
The class in your case might be something like this:
class LaravelWorker extends Thread
{
private $object;
public function __construct($object)
{
$this->object = $object;
}
public function run()
{
$object->runProcedure();
}
}
And you can call it at your code such as this:
$object = new ObjectWithProcedure();
$threadedMethod = new LaravelWorker($object);
$threadedMethod->start();
If, for some reason, you need to wait until the $threadedMethod finishes, you can do
$threadedMethod->join();
(more_code...)
And the more_code section will only execute once $threadedMethod has ended.
Hope it helps!

PHP thread do not end

I tried to implement multithreading in php to fetch data from a data source parallely.
But in the process, the threads i create to fetch the data continue to remain in the memory, even after the fetching.
This is the class that i call
class ClassName extends Thread {
public function __construct($i){
$this->i=$i;
}
public function run(){
// functionCallToDataSource($this->i);
}
}
and i call this class here (in a loop).
$workers = new ClassName(parameter);
$workers->start();
$workers->kill(); //this isnt working
This kill() doesnt seem to work for me, as the memory is not reduced after the functions have been performed.
I have to restart my server to free the blocked memory

PHP - Object Oriented Practices and Inheritance

This is the basic class design
class CustomModule {
public __construct() { }
//Run me first automaticly
public function exec($str) { }
}
class Randomizer extends CustomModule {
public __construct() { }
//Call me
public function exec($str) { }
}
As I am designing a plugin/module system for extern developers I need the CustomModule->exec() to run first, I do not want to leave it up to the devs to have to call base->exec($str).
I want CustomModule::exec() called automaticly before Randomizer::exec() is called without having to put code in Randomizer::exec(). Is This Possible perhaps with magic function?
In my opinion, i would use this way:
Instead of calling _construct in exec of Randomizer, you can define a constructor in Randomizer and call parent::_construct
class CustomModule {
//Run me first automaticly
public function exec($str) { }
public __construct($str) {
$this->exec($str);
}
}
class Randomizer extends CustomModule {
//Call me
public function exec($str) {
parent::__construct($str);
}
}
If your object requires some initialization before you can "release* it into the rest of application, then it means that you need a factory for this. This is how you should be solving it, if you require to call some method only once.
If such execution happens each time you call exec() method, then instead you should be using some sort of containment (in a form of decorator or just you standard composition of objects).
Basically, you need to restructure your code.
After a bit more thought I realized this is BAD design. I have to keep the code base simple and scaleable and this would only make a mess in large projects.
As the only program calling the Randomizer::exec() is my inhouse built program I can just call CustomModule::exec() on the previous line and get a boolean response to see if it should continue to the next line.
Sorry to have to end this Q' short

A new Instances of Singleton Class in PHP for each HTTP request

I have the following Singleton Class in PHP.
class CounterBalance{
private static $instance;
private $counterBalance;
private function __construct(){
$this->counterBalance = mt_rand(1, 4);
}
// Getter method for creating/returning the single instance of this class
public final static function getInstance() {
if(!self::$instance) {
self::$instance = new CounterBalance();
echo "CounterBalance constructed <br/>";
}
return self::$instance;
}
public function getCounterBalanceValue() {
return $this->counterBalance;
}
}
But in the class when I do something like
CounterBalance::getInstance()->getCounterBalanceValue();
on the same php page, it works properly. But it not working properly across pages. I get more than one instance of CounterBalance, when I do the same function call in the subsequent php page.
Can anyone one please explain why this happens.
Thanks in advance.
Welcome to the stateless world of HTTP.
A singleton can only persist for the single page load (or any other PHP data structure, for that matter). When the php process dies, the singleton dies with it. The next time a page is loaded the singleton is created all over again. The singleton is only alive in the context of that single process. If you tried to create ten instances of it during a single script execution you would maintain the single instance.
If you need data persistence across pages you'll have to implement an agent of state. For example, the $_SESSION or $_GET superglobals or store data in a database (for example) and re-retrieve it on subsequent page loads.

Categories