Problème hiérarchie de classes php.

WRInaute accro
Bonjour

Avec le livre : "Mastering Modern Payments with Stripe" de Pete Keen, j'élabore une hiérarchie de classes php, dont : ( du plus générique au plus spécialisé ) :

Stripe => FSMStripe => ApplicationController => SalesController => Sale.

Le bug... Je lance le FSM dans ApplicationController. Celà signifie déclarer les états du FSM et les fonctions de transition entre états, dans ApplicationController.

Mais... je lance PHP_Resque et le BackgroundWorker également dans ApplicationController, mais je dois lancer ( à partir des fonctions du FSM et à partir du BackgroundWorker ), des fonctions déclarées dans Sale.

Le FSM et le BackgroundWorker se lancent correctement, mais comment lancer à partir des cette classe ApplicationController, les fonctions de Sale ?

C'est le problème : Les classes de départ donne le service, mais si j'essaye de disposer de ce service dans des classes profodne dérivées, je vais avoir à chaque fois une floppée d'intrusctions.

Je peux fournir du code si besoin.

Merci beaucoup de votre réponse.

Cordialement.
 
WRInaute accro
Bonjour spout

Les traits, ce sont des fonctions accessibles effectivement, mais quelle est la logique de déclarer des fonctions détachées de toute instanciation de classe ?

Et surtout, comment déclarer des fonctions génériques dans ApplicationController, qui fassent ce qu'il faut, en fonction de la classe dérivée qui les lance ?

Equivalent de switch case, mais de manière dynamique ?

Tu vois à quel point de nullité je suis en poo.

Respectueusement.
 
Nouveau WRInaute
Je peux fournir du code si besoin.
Oui, ça sera plus clair

Sans rentrer trop dans les détails, que cherche tu à faire au final ?

Et surtout, comment déclarer des fonctions génériques dans ApplicationController, qui fassent ce qu'il faut, en fonction de la classe dérivée qui les lance ?

Tu peur créer un méthode "toto" dans ApplicationController ou mieux, une interface avec les méthodes souhaitées (dans ce cas ApplicationController implémente cette interface)

Puis tu les surcharges dans tes classes filles.
Comme ça t'appelle toujours la méthode "toto".
 
Dernière édition:
WRInaute accro
Bonjour Wolowizard et Spout ;)

J'ai tout mis dans le trait StripeFunctions , qui est dans ApplicationController.

Le FSM fonctionne, mais la fonction perform() n'est pas lancée.

Celà vient probablement du fait que je n'ai pas lancé php_resque en CLI avec QUEUE.

Mais, je confond un peu Redis ( chargé de la persistance/database ), et PHP_Resque.

J'ai moins besoin de conseils sur l'architecture, que d'explications sur les lancements de Redis et PHP_Resque.

Les instructions MySQL en ORM perso, çà marche, j'ai simplement besoin que les services fonctionnent.

Merci beaucoup pour votre aide.

Respectueusement.


Code:
<?php
trait StripeFunctions
{
    function SQLChaine($val)
    {
        return ( "'".str_replace("'","''",$val)."'" );
    }
    function uniqidReal($lenght = 32)
    {
        // uniqid gives 13 chars, but you could adjust it to your needs.
        if (function_exists("random_bytes"))
        {
            $bytes = random_bytes(ceil($lenght / 2));
        }
        elseif (function_exists("openssl_random_pseudo_bytes"))
        {
            $bytes = openssl_random_pseudo_bytes(ceil($lenght / 2));
        }
        else
        {
            throw new Exception("no cryptographically secure random function available");
        }
        return substr(bin2hex($bytes), 0, $lenght);
    }
    public function update($params)
    {
        foreach($params as $key => $value)
        {
            $this->$key = $value;
            $this->sale[$this->SQLChaine($key)] = $value;
        }
    }
    public function update_attributes($params)
    {
        $this->update($params);
    }
    /*
    * State : before Sale.save()
    */
    public function populate_gid()
    {
        while(true)
        {
            unset($tmp_id);
            $tmp_id = $this->uniqidReal();
            unset($tmp_guid);
            $tmp_guid = $this->conn->TABLE('SALES')->WHERE('guid', '=', $this->SQLChaine($tmp_id))->VALUE('guid');
            /*
            * On prend
            * le premier
            * guid non enregistre.
            *
            * On ne l'enregistre
            * qu'avec save(),
            * car guid est
            * tres aleatoire.
            */
            if(empty($tmp_guid))
            {
                $this->guid = $tmp_id;
                break;
            }
        }
        return($this->guid);
    }
    /*
    * State : before Sale.populate_guid()
    */
    public function authenticate_user($params)
    {
        if($params['password'] !== $params['password_confirmation'])
        {
            throw new Exception('Les deux password different.');
            return(null);
        }
        /*
        * password doit-il
        * être crypté
        * dans USERS ?
        */
        $tmp_user_id = $this->conn->TABLE('USERS')->WHERE([['email', '=', SQLChaine($params['email'])],['password', '=', SQLChaine($params['password'])]])->VALUE('id');
        if(empty($tmp_user_id))
        {
            throw new Exception('Donnees de conexion fausses.');
            return(false);
        }
        $this->id                       = $tmp_user_id;
        $this->user_params = $params;
        $this->email                    = $params['email'];
        return($this);
    }
    function create($params)
    {
        $this->update($params);
        return($this);
        /*
        * Sale.
        */
        try {
            $this->product = $this->products()->find($this->params['product_id']);
        }   
        catch ( Cartalyst\Stripe\Exception\NotFoundException $e) {
            // Get the status code
            $code = $e->getCode();
            // Get the error message returned by Stripe
            $message = $e->getMessage();
            // Get the error type returned by Stripe
            $type = $e->getErrorType();
            echo "Error Code = " . $code . "\tMessage Stripe : " . $message . "\tType = " . $type . "<br />\n";
            return(false);
        }
        $this->sale = parent::create([
            'amount'        => $this->product->price,
            'email'         => $this->params['email'],
            'stripe_token'  => $this->params['stripeToken']]);
        return(true);
    }
    public function save()
    {
        /*
        * Fin de
        * la fonction.
        */
        $this->guid = $this->populate_gid();
        try {
            $this->conn->TABLE('SALES')->INSERT(array('guid' => $this->SQLChaine($this->guid), 'email' => $this->SQLChaine($this->email), 'product_id' => $this->SQLChaine($this->product_id), 'charge_id' => $this->SQLChaine($this->stripe_id), 'card_expiration' => $this->SQLChaine($this->card_expiration), 'amount' => $this->amount, 'fee_amount' => $this->fee_amount, 'error' => $this->SQLChaine($this->error)));
        }
        catch (Exception $e ) {
            // Get the status code
            $code = $e->getCode();
            // Get the error message returned by Stripe
            $message = $e->getMessage();
            // Get the error type returned by Stripe
            $type = $e->getErrorType();
            echo "Error Code = " . $code . "\tMessage Stripe : " . $message . "\tType = " . $type . "<br />\n";
            return(false);
        }
        return(true);
    }
    public function find_by($guid)
    {
        $tmp_array_sale = $this->conn->TABLE('SALES')->WHERE('guid', '=', $this->SQLChaine($guid))->SELECT('guid', 'email', 'product_id')->FIRST();
        if(!empty($tmp_array_sale['guid']))
        {
            /*
            * Update
            * de l'attribut
            * $this->sale
            * de Sale.
            */
            $this->update($tmp_array_sale);
            return($this->sale);
        }
        else
        {
            return(false);
        }
    }
/*
    event: process after: :charge_card
    {
        transition from : pending to :processing
            save();
        event: process after: :charge_card
    }
    event: finish
    {
        transition from : processing pending to :finished
    }
    event: fail
    {
        transition from : processing pending to :errored
    }
 */
    /*
    * Declenche apres
    * sale.save(), 
    * par :process.
    */
    public function charge_card()
    {
        try {
            $charge = $this->charges()->create([
                'amount'        => $this->amount,
                'currency'      => 'EUR',
                'source'        => $this->stripe_token,
                'description'   => $this->email]);
        } catch ( Cartalyst\Stripe\Exception\BadRequestException $e ) {
            // Get the status code
            $code = $e->getCode();
            // Get the error message returned by Stripe
            $message = $e->getMessage();
            // Get the error type returned by Stripe
            $type = $e->getErrorType();
            $this->update_attributes(['error' => $message]);
            echo "Error Code = " . $code . "\tMessage Stripe : " . $message . "\tType = " . $type . "<br />\n";
            return(false);
            /*
            * Action
            * sur le FSM.
            */
            //    $this->fail!;
        }
        /*
        * Action
        * sur le FSM.
        */
        //    event $this->finish! :
        try {
            $balance = $this->balance()->find($charge->balance_transaction);
        } catch ( Cartalyst\Stripe\Exception\NotFoundException $e ) {
            // Get the status code
            $code = $e->getCode();
            // Get the error message returned by Stripe
            $message = $e->getMessage();
            // Get the error type returned by Stripe
            $type = $e->getErrorType();
            $this->update_attributes(['error' => $message]);
            echo "Error Code = " . $code . "\tMessage Stripe : " . $message . "\tType = " . $type . "<br />\n";
            return(false);
        }
        /*
        * Fonction
        * updatant
        * les attributs
        * de Sale.
        */
        $this->update([
            'stripe_id'        => $charge.id,
            'card_expiration'    => $charge->source->expr_year . "-" . $charge->source->exp_month . "-1",
            'fee_amount'        => $balance->fee]);
        return(true);
    }
    /*
    * Pour render
    * en cas d'erreeur.
    */
    public function first()
    {
        try {
            $this->product = $this->products()->find($this>product_id);
        } catch ( Cartalyst\Stripe\Exception\NotFoundException $e ) {
            // Get the status code
            $code = $e->getCode();
            // Get the error message returned by Stripe
            $message = $e->getMessage();
            // Get the error type returned by Stripe
            $type = $e->getErrorType();
            echo "Error Code = " . $code . "\tMessage Stripe : " . $message . "\tType = " . $type . "<br />\n";
            return(false);
        }
        return(true);
    }
    public function pickup()
    {
        $this->sale = $this->find_by($this->params['guid']);
        /*
        * 1 seul Product
        * dans Sale ?
        */
        if($this->sale !== false)
        {
            try {
                $this->product = $this->products()->find($this->product_id);
            } catch ( Cartalyst\Stripe\Exception\NotFoundException $e ) {
                // Get the status code
                $code = $e->getCode();
                // Get the error message returned by Stripe
                $message = $e->getMessage();
                // Get the error type returned by Stripe
                $type = $e->getErrorType();
                echo "Error Code = " . $code . "\tMessage Stripe : " . $message . "\tType = " . $type . "<br />\n";
                return(false);
            }
        }
        return(true);
    }
/*   
    "before_create";
    "process";
    "finished";
    "fail";
    Sale :
    States  Transitions
    START   TO_PENDING      - lecture BDD.
                authenticate_user()
    PENDING TO_PROCESSING   - Stripe.
                sale_controller.create(),
    PROCESSING TO_FINISHED  - Enreg BDD.
                sale.save(),
                - Stripe.
                sale.charge_card(),
    FINISHED
    ou
    ERROR                   ( si pas de transition ).
 */
    function sigint()
    {
        exit;
    }
    public function first_init()
    {
        $settings = [
            'REDIS_BACKEND'        => '127.0.0.1:6379',    // Set Redis Backend Info
            'REDIS_BACKEND_DB'    => '0',                 // Use Redis DB 0
            'COUNT'            => '1',                 // Run 1 worker
            'INTERVAL'        => '5',                 // Run every 5 seconds
            'APP_INCLUDE'        => __DIR__ . '/init.php',
            'QUEUE'            => '*',                 // Look in all queues
            'PREFIX'        => 'test',              // Prefix queues with test
        ];   
        foreach ($settings as $key => $value) {
            putenv(sprintf('%s=%s', $key, $value));
        }
/*
        $loader = require __DIR__ . '/../../PHP_Resque/PHP_Resque/vendor/autoload.php';
        $loader->add('Resque_Tests', __DIR__);
        define('TEST_MISC', realpath(__DIR__ . '/misc'));
        define('REDIS_CONF', TEST_MISC . '/redis.conf');
        // Attempt to start our own redis instance for tesitng.
        exec('which redis-server', $output, $returnVar);
        if($returnVar != 0)
        {
            echo "Cannot find redis-server in path. Please make sure redis is installed.\n";
            exit(1);
        }
        exec('cd ' . TEST_MISC . '; redis-server ' . REDIS_CONF, $output, $returnVar);
        usleep(500000);
        if($returnVar != 0) {
            echo "Cannot start redis-server.\n";
            exit(1);
        }
        // Get redis port from conf
        $config = file_get_contents(REDIS_CONF);
        if(!preg_match('#^\s*port\s+([0-9]+)#m', $config, $matches)) {
            echo "Could not determine redis port from redis.conf";
            exit(1);
        }
        Resque::setBackend('localhost:' . $matches[1]);
        register_shutdown_function(array($this, 'killRedis'), getmypid());
        if(function_exists('pcntl_signal'))
        {
            // Override INT and TERM signals, so they do a clean shutdown and also
            // clean up redis-server as well.
            pcntl_signal(SIGINT, array($this, 'sigint'));
            pcntl_signal(SIGTERM, array($this, 'sigint'));
        }
 */
    }
    /*
    // Shutdown
    function killRedis($pid)
    {
        if (getmypid() !== $pid)
        {
            return; // don't kill from a forked worker
        }
        $config = file_get_contents(REDIS_CONF);
        if(!preg_match('#^\s*pidfile\s+([^\s]+)#m', $config, $matches))
        {
            return;
        }
        $pidFile = TEST_MISC . '/' . $matches[1];
        if (file_exists($pidFile))
        {
            $pid = trim(file_get_contents($pidFile));
            posix_kill((int) $pid, 9);
            if(is_file($pidFile)) {
                unlink($pidFile);
            }
        }
        // Remove the redis database
        if(!preg_match('#^\s*dir\s+([^\s]+)#m', $config, $matches))
        {
            return;
        }
        $dir = $matches[1];
        if(!preg_match('#^\s*dbfilename\s+([^\s]+)#m', $config, $matches))
        {
            return;
        }
        $filename = TEST_MISC . '/' . $dir . '/' . $matches[1];
        if(is_file($filename)) {
            unlink($filename);
        }
    }
    */
    /*
    * Processus
    * de vente
    * d'un service
    * ( pas un Product ).
    *
    * Voir le formulaire
    * v3 Elements Stripe
    * sur internet,
    * avec  email
    * et name..
    */
/*
    $symbol est une valeur
    qui si elle est
    rencontree, permet
    a la fonction
    de transition
    de s'executer.
    $payload est une array
    permetant d'enregistrer
    les donnees a traiter,
    en mode LIFO
    ( structure de stack 
    avec array_push($symbol)
    et array_pop_($symbol) ).
 */
    public function createFSM()
    {
        $this->fsm = new FSM('START', $this->stack);
        $this->fsm->addTransition('TO_PENDING', 'START', 'PENDING', array($this, 'StartCallback'));
        $this->fsm->addTransition('TO_PROCESSING', 'PENDING', 'PROCESSING', array($this, 'PendingCallback'));
        $this->fsm->addTransition('TO_FINISHED', 'PROCESSING', 'FINISHED', array($this, 'ProcessingCallback'));
        $this->fsm->process('TO_PENDING');
        $this->fsm->process('TO_PROCESSING');
        $this->fsm->process('TO_FINISHED');
        $this->fsm->setDefaultTransition('START', array($this, 'StartErrorCallback'));
        $this->fsm->setDefaultTransition('PENDING', array($this, 'PendingErrorCallback'));
        $this->fsm->setDefaultTransition('PROCESSSING', array($this, 'ProcessingErrorCallback'));
    }
/*
    $symbol est une valeur
    qui si elle est
    rencontree, permet
    a la fonction
    de transition
    de s'executer.
    $payload est une array
    permetant d'enregistrer
    les donnees a traiter,
    en mode LIFO
    ( structure de stack 
    avec array_push($symbol)
    et array_pop_($symbol) ).
 */
    public function second_init()
    {
        $this->createFSM();
        $this->ProcessId = Resque::enqueue('default', 'Sale', array(), true);
    }
    public function StartCallback($symbol, &$payload, $currentState, $nextState)
    {
        $this->guid = $this->populate_gid();
        //        $this->create($this->params);
        echo "TO_PENDING Transition\n";
        return(true);
    }
    public function setUp()
    {
        file_put_contents("result.txt", "Avant debut Worker.\n");
//        echo "Avant debut Worker.\n";
        return(true);
    }
    public function tearDown()
    {
        file_put_contents("result.txt", "Apres fin Worker.\n");
        echo "Apres fin Worker.\n";
        return(true);
    }
    public function perform()
    {
        file_put_contents("result.txt", "Avant premiere fonction.\n");
        echo "Avant premiere fonction.\n";
        /*
        if($this->save() === false)
        {
            return(false);
        }
        */
        file_put_contents("result.txt", "Premiere fonction passee.\n");
        echo "Premiere fonction passee.\n";
        /*
        if($this->charge_card() === false)
        {
            return(false);
        }
        */
        file_put_contents("result.txt", "Deuxieme fonction passee.\n");
        echo "Deuxieme fonction passee.\n";
        return(true);
    }
    public function PendingCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "TO_PROCESSING Transition\n";
        return(true);
    }
    public function ProcessingCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "TO_FINISHED Transition\n";
        return(true);
    }
    public function StartErrorCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "This symbol does not compute: $symbol\n";
    }
    public function PendingErrorCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "This symbol does not compute: $symbol\n";
    }
    public function ProcessingErrorCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "This symbol does not compute: $symbol\n";
    }
    public function FinishedErrorCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "This symbol does not compute: $symbol\n";
    }
    //  sale.process lance : sale.save() puis sale.charge_card().
}
?>
 
WRInaute accro
Bonjour Monsieur spout

J'ai donc mis les fonctions dans le trait StripeFunctions, qui est inclus dans ApplicationController.

La classe Sale ci-dessous, ( ce devrait être SalesController je sais ), lance first_init() et second_init() ( voir le trait ).

J'ai quizzé au départ le fait que c"est Sale qui avait accès aux fonctions, et je voulais ( fonctions dans Sale ), lancer les fonctions à partir de SalesController ( pas possible Sale est dérivée de SalesController ).

Maintenant, le FSM ne démarre plus ( dans le trait ), alors qu'avant il démarrait, à partir de SalesController, qui appelait createFSM() de sa classe père ApplicationController.

Le Worker n'a jamais marché, ( c'est le problème que j'ai ), certainement parce qu'il n'est pas lancé du tout, en mode CLI.

En fait, je ne sais pas comment lancer le PHP_Resque ( BackgroundWorker ), parce que la doc de PHP_Resque est peu compréhensible.

Merci beaucoup de votre aide.

Respectueusement.


Code:
<?php
require_once(__DIR__ . '/SalesController.php');
class Sale  extends SalesController
{
    /******************************************************************************************************************
    Classification des events de la FSM :
    ( quel statut de before_create ? )
    :process    ->    transition from :pending to :processing      -> :after    ->    charge_card()
    :finish
    ou :
    :fail
    Sequencement des fonctions :
    authenticate_user() -> populate_guid() -> sale.create() -> :process -> sale.save() -> sale.charge_card() -> 
    before action : first ou create : authenticate_user();
    ******************************************************************************************************************/
    /*
    1 Sale a 1 ou + Product.
    Parametres de Sale :
    $state, $stripe_id, $stripe_token, $card_expiration, $error, $fee_amount, $amount, $email, $guid, $ref_products, $others
    */
    public $guid            = null;
    public $sale            = array();
    public $stripe            = null;
    public $sale_state        = null;    /* Valeurs : "before_first_action", "before_create", "process", "finished", "fail" */
    public $state            = null;
    public $stripe_id        = null;
    public $stripe_token        = null;
    public $card_expiration    = null;
    public $params        = null;
    public $email        = null;
    public $amount        = null;
    public $fee_amount        = null;
    public $error        = null;
    public $product_id        = null;
    public $product        = null;
    function __construct($params) 
    {
        parent::__construct($params);
        $this->params = $params;
        $this->update($params);
        $this->first_init();
        $this->second_init();
        $this->ProcessId = Resque::enqueue('default', $this, array(), true);
        return($this);
    }
/*
    event: process after: :charge_card
    {
        transition from : pending to :processing
            save();
        event: process after: :charge_card
    }
    event: finish
    {
        transition from : processing pending to :finished
    }
    event: fail
    {
        transition from : processing pending to :errored
    }
 */
}
/*
$params = array();
$sale = new Sale($params);
print_r($sale);
 */
?>
 
WRInaute accro
Bonjour

Le BackgroundWorker se lance, mais erreur quand la classe de Job a un paramètre.

Ci-dessous Sale.php, et StripeFunctions.php.

J'ai séparé la classe SaleWorker ( avec perform() etc... ), de Sale, car le paramètre $params de Sale provoquait une erreur.

Je ne sais pas comment programmer une classe de Job, avec paramètre(s) dans le constucteur.

Pour ce qui est du lancement du Worker ( dans le trait StripeFunctions ), je pense que je pourrais laisser le début de first_init(), le reste relance le Worker inutilement.

Par ailleurs, le $this de Sale ne peut pas être transmis à SaleWorker ( seulement comme une array ), donc il est impossible de lancer dans cette classe, des méthodes de Sale.

Donc, ma question reste : Comment lancer ( avec paramètres ) , une méthode de classe de Job, alors que en apparence, PHP_Resque me rejette quand il y a un paramètre dans son constructeur ?

Merci beaucoup de votre réponse.

Cordialement.


PHP:
<?php

/*** Sale.php ***/

require_once(__DIR__ . '/SalesController.php');
require_once(__DIR__ . '/StripeFunctions.php');

class SaleWorker
{
    public function setUp()
    {
        echo "Avant debut Worker.\n";
        return(true);
    }
    public function tearDown()
    {
        echo "Apres fin Worker.\n";
        return(true);
    }
    public function perform()
    {
        echo "Avant premiere fonction.\n";
        print_r($this->args);
        if($this->args->save() === false)
        {
            return(false);
        }
        echo "Premiere fonction passee.\n";
        if($this->args->charge_card() === false)
        {
            return(false);
        }
        echo "Deuxieme fonction passee.\n";
        Resque::dequeue('default', '[SaleWorker]');
        return(true);
    }
}
class Sale  extends SalesController
{
    use StripeFunctions;
    /******************************************************************************************************************
    Classification des events de la FSM :
    ( quel statut de before_create ? )
    :process    ->    transition from :pending to :processing      -> :after    ->    charge_card()
    :finish
    ou :
    :fail
    Sequencement des fonctions :
    authenticate_user() -> populate_guid() -> sale.create() -> :process -> sale.save() -> sale.charge_card() -> 
    before action : first ou create : authenticate_user();
    ******************************************************************************************************************/
    /*
    1 Sale a 1 ou + Product.
    Parametres de Sale :
    $state, $stripe_id, $stripe_token, $card_expiration, $error, $fee_amount, $amount, $email, $guid, $ref_products, $others
    */
    public $guid            = null;
    public $sale            = array();
    public $stripe            = null;
    public $sale_state        = null;    /* Valeurs : "before_first_action", "before_create", "process", "finished", "fail" */
    public $state            = null;
    public $stripe_id        = null;
    public $stripe_token        = null;
    public $card_expiration    = null;
    public $params        = null;
    public $email        = null;
    public $amount        = null;
    public $fee_amount        = null;
    public $error        = null;
    public $product_id        = null;
    public $product        = null;
    function __construct($params) 
    {
        parent::__construct($params);
        $this->params = $params;
        $this->update($params);
        $this->first_init();
        $this->ProcessId = Resque::enqueue('default', 'SaleWorker', $this, true);
        echo "\t\tProcessId = " . $this->ProcessId . "\n";
        return($this);
    }
    public function update($params)
    {
        foreach($params as $key => $value)
        {
            $this->$key = $value;
            $this->sale[$this->SQLChaine($key)] = $value;
        }
    }
    public function update_attributes($params)
    {
        $this->update($params);
    }

  }

$params = array('amount' => 50);
$sale = new Sale($params);
// $sale->update($params);
// print_r($sale);
?>


<?php

/** StripeFunctions.php  **/

trait StripeFunctions
{
    public function first_init()
    {
        $settings = [
            'REDIS_BACKEND'        => '127.0.0.1:6379',    // Set Redis Backend Info
            'REDIS_BACKEND_DB'    => '0',                 // Use Redis DB 0
            'COUNT'            => '1',                 // Run 1 worker
            'INTERVAL'        => '5',                 // Run every 5 seconds
//            'APP_INCLUDE'        => __DIR__ . '/init.php',
            'QUEUE'            => '*',                 // Look in all queues
            'PREFIX'        => 'test',              // Prefix queues with test
        ];   
        foreach ($settings as $key => $value) {
            putenv(sprintf('%s=%s', $key, $value));
        }
//        require __DIR__ . '/../../PHP_Resque/PHP_Resque/vendor/autoload.php';
        require __DIR__ . '/../../PHP_Resque/PHP_Resque/bin/resque';
        date_default_timezone_set('GMT');
        define('TEST_MISC', realpath(__DIR__ . '/misc'));
        define('REDIS_CONF', TEST_MISC . '/redis.conf');
        // Attempt to start our own redis instance for tesitng.
        exec('which redis-server', $output, $returnVar);
        if($returnVar != 0)
        {
            echo "Cannot find redis-server in path. Please make sure redis is installed.\n";
            exit(1);
        }
        exec('cd ' . TEST_MISC . '; redis-server ' . REDIS_CONF, $output, $returnVar);
        usleep(500000);
        if($returnVar != 0) {
            echo "Cannot start redis-server.\n";
            exit(1);
        }
        // Get redis port from conf
        $config = file_get_contents(REDIS_CONF);
        if(!preg_match('#^\s*port\s+([0-9]+)#m', $config, $matches)) {
            echo "Could not determine redis port from redis.conf";
            exit(1);
        }
        Resque::setBackend('localhost:' . $matches[1]);

        register_shutdown_function(array($this, 'killRedis'), getmypid());
        if(function_exists('pcntl_signal'))
        {
            // Override INT and TERM signals, so they do a clean shutdown and also
            // clean up redis-server as well.
            pcntl_signal(SIGINT, array($this, 'sigint'));
            pcntl_signal(SIGTERM, array($this, 'sigint'));
        }
    }
    // Shutdown
    function killRedis($pid)
    {
        if (getmypid() !== $pid)
        {
            return; // don't kill from a forked worker
        }
        $config = file_get_contents(REDIS_CONF);
        if(!preg_match('#^\s*pidfile\s+([^\s]+)#m', $config, $matches))
        {
            return;
        }
        $pidFile = TEST_MISC . '/' . $matches[1];
        if (file_exists($pidFile))
        {
            $pid = trim(file_get_contents($pidFile));
            posix_kill((int) $pid, 9);
            if(is_file($pidFile)) {
                unlink($pidFile);
            }
        }
        // Remove the redis database
        if(!preg_match('#^\s*dir\s+([^\s]+)#m', $config, $matches))
        {
            return;
        }
        $dir = $matches[1];
        if(!preg_match('#^\s*dbfilename\s+([^\s]+)#m', $config, $matches))
        {
            return;
        }
        $filename = TEST_MISC . '/' . $dir . '/' . $matches[1];
        if(is_file($filename)) {
            unlink($filename);
        }
    }

?>
 
WRInaute accro
Rebonjour

Voici un exemple plus simple.

Cà marche, les fonctions de SaleWorker sont bien déclenchées.

En bref, je ne sais pas comment lancer dans la classe SaleWorker, une fonction de la classe Sale.

Le PHP_Resque que j'utilise est maintenant celui de mjphaynes de GitHub, et je crois qu'il m'est impossible de lancer une fonction de Sale ( qui est une classe instanciée non statique ), à partir de la classe SaleWorker, dont le constructeur semble-t-il, ne doit pas avoir de paramètre.

SaleWorker est le Job lancé en background par Sale.

Que faire ?

Merci beaucoup de vos réponses.

Très respectueusement.


Code:
<?php
require_once(__DIR__ . '/SalesController.php');
require_once(__DIR__ . '/StripeFunctions.php');
require __DIR__ . '/../../PHP_Resque/vendor/autoload.php';
class SaleWorker
{
    public function setUp()
    {
        file_put_contents(__DIR__ . "/result_avant.txt", "Avant debut Worker.\n");
        echo "Avant debut Worker.\n";
        return(true);
    }
    public function tearDown()
    {
        file_put_contents(__DIR__ . "/result_apres.txt", "Apres fin Worker.\n");
        echo "Apres fin Worker.\n";
        return(true);
    }
    public function perform($args)
    {
        file_put_contents(__DIR__ . "/result1.txt", "Avant premiere fonction.\n");
        echo "Avant premiere fonction.\n";
        /*
        if($this->save() === false)
        {
            return(false);
        }
        */
        file_put_contents(__DIR__ . "/result2.txt", "Premiere fonction passee.\n");
        echo "Premiere fonction passee.\n";
        /*
        if($this->charge_card() === false)
        {
            return(false);
        }
        */
        file_put_contents(__DIR__ . "/result3.txt", "Deuxieme fonction passee.\n");
        echo "Deuxieme fonction passee.\n";
        return(true);
    }
}
class Sale  extends SalesController
{
    use StripeFunctions;
    public $guid            = null;
    public $sale            = array();
    public $stripe            = null;
    public $sale_state        = null;    /* Valeurs : "before_first_action", "before_create", "process", "finished", "fail" */
    public $state            = null;
    public $stripe_id        = null;
    public $stripe_token        = null;
    public $card_expiration    = null;
    public $params        = null;
    public $email        = null;
    public $amount        = null;
    public $fee_amount    = null;
    public $error        = null;
    public $product_id    = null;
    public $product        = null;
    function __construct($params) 
    {
        parent::__construct($params);
        $this->params = $params;
        $this->update($params);
//        \Resque::loadConfig('config.yml');
//        $this->first_init();
        $Process = Resque::push('SaleWorker', $params);
        $ProcessId = $Process->getId();
       
        echo "\t\tProcessId = " . $ProcessId . "\n";
        $job = Resque\Job::load($ProcessId);
       
        $status = $job->getStatus();
        switch ($status) {
        case Resque\Job::STATUS_WAITING : 
                echo "Job is still queued.\n";
                break;
        case Resque\Job::STATUS_DELAYED : 
                echo "Job is delayed.\n";
                break;
        case Resque\Job::STATUS_RUNNING : 
                echo "Job is currently running.\n";
                break;
        case Resque\Job::STATUS_COMPLETE : 
                echo "Job is complete.\n";
                break;
        case Resque\Job::STATUS_CANCELLED : 
                echo "Job has been cancelled.\n";
                break;
        case Resque\Job::STATUS_FAILED : 
                echo "Job has failed.\n";
                break;
        case false : 
                echo "Failed to fetch the status - is the id valid?\n";
                break;
       
        default :
                echo "Status unknown.\n";
                break;
        }
        return($this);
    }
    public function update($params)
    {
        foreach($params as $key => $value)
        {
            $this->$key = $value;
            $this->sale[$this->SQLChaine($key)] = $value;
        }
    }
    public function update_attributes($params)
    {
        $this->update($params);
    }
}
$params = array('amount' => 50);
$sale = new Sale($params);
?>
 
WRInaute accro
Dernières nouvelles

J'ai mis tout en statique.

Voici ce que celà donne.

Le bug... La classe Sale n'est pas visible dans le perform().

Comment lancer une fonction de classe à partir d'un BackgroundWorker tel que PHP_Resque ( auteur mjphaynes ) ?

Le Job ne peut être que dans une classe extérieure à celle des fonctions.

Merci beaucoup.

Respectueusement.


PHP:
<?php
require    __DIR__ . '/SalesController.php';
require __DIR__ . '/../../../PHP_Resque/vendor/autoload.php';
require    __DIR__ . '/StripeFunctions.php';
class SaleWorker
{
    public function setUp()
    {
        return(true);
    }
    public function tearDown()
    {
        return(true);
    }
    public function perform($args)
    {
        echo "\t\tDebut Perform().\n";
        if(Sale::save($args['new_conn']) === false)
        {
            return(false);
        }
        echo "\t\tMilieu Perform().\n";
        if(Sale::charge_card($args['stripe']) === false)
        {
            return(false);
        }
        echo "\t\tFin Perform().\n";
        return(true);
    }
}
class Sale extends SalesController
{
    use StripeFunctions;
    /******************************************************************************************************************
    Classification des events de la FSM :
    ( quel statut de before_create ? )
    :process    ->    transition from :pending to :processing      -> :after    ->    charge_card()
    :finish
    ou :
    :fail
    Sequencement des fonctions :
    authenticate_user() -> populate_guid() -> sale.create() -> :process -> sale.save() -> sale.charge_card() ->
    before action : first ou create : authenticate_user();
    ******************************************************************************************************************/
    /*
    1 Sale a 1 ou + Product.
    Parametres de Sale :
    $state, $stripe_id, $stripe_token, $card_expiration, $error, $fee_amount, $amount, $email, $guid, $ref_products, $others
    */
    public static $Process        = null;
    public static $ProcessId    = null;
    public static $status        = null;
    public static $guid        = null;
    public static $sale        = array();
    public $new_conn        = array();
    public $stripe            = array();
    public static $sale_state    = null;    /* Valeurs : "before_first_action", "before_create", "process", "finished", "fail" */
    public $state            = null;
    public static $stripe_id    = null;
    public static $stripe_token    = null;
    public static $card_expiration    = null;
    public static $params        = null;
    public static $email        = '';
    public static $amount        = 0;
    public static $fee_amount    = 0;
    public static $error        = null;
    public static $product_id    = null;
    public static $product        = null;
    public static function init($params)
    {
        parent::init($params);
        self::$sale_state    = "before_first_action";
        $params['stripe'] = new StripeFSM();
        self::$params    = $params;
        self::update(self::$params);
        self::updateSale(self::$params);
        parent::createFSM();
        //        print_r($params);
        //        self::$new_conn = $params['new_conn'];
        //        print_r(self::$new_conn);
        self::$email = self::uniqidReal();
        /**
        *
        Resque::push(function($job) {
            echo 'This is a inline job #'.$job->getId().'!';
    });
    *
        **/
        return;
    }
    public static function StartCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "TO_PENDING Transition1\n";
    }
    public static function PendingCallback($symbol, &$payload, $currentState, $nextState)
    {
        self::$Process = Resque::push('SaleWorker', self::$params);
                self::$ProcessId = self::$Process->getId();
                echo "\t\tProcessId = " . self::$ProcessId . "\n";
                $job = Resque\Job::load(self::$ProcessId);
                self::$status = $job->getStatus();
               switch (self::$status) {
                case Resque\Job::STATUS_WAITING :
                        echo "Job is still queued.\n";
                        break;
                case Resque\Job::STATUS_DELAYED :
                        echo "Job is delayed.\n";
                        break;
                case Resque\Job::STATUS_RUNNING :
                        echo "Job is currently running.\n";
                        break;
                case Resque\Job::STATUS_COMPLETE :
                        echo "Job is complete.\n";
                        break;
                case Resque\Job::STATUS_CANCELLED :
                        echo "Job has been cancelled.\n";
                        break;
                case Resque\Job::STATUS_FAILED :
                        echo "Job has failed.\n";
                        break;
                case false :
                        echo "Failed to fetch the status - is the id valid?\n";
                        break;
                default :
                        echo "Status unknown.\n";
                        break;
                }
        echo "TO_PROCESSING Transition2\n";
    }
    public static function ProcessingCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "TO_FINISHED Transition3\n";
    }
    public static function StartErrorCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "This symbol does not compute: $symbol\n";
    }
    public static function PendingErrorCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "This symbol does not compute: $symbol\n";
    }
    public static function ProcessingErrorCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "This symbol does not compute: $symbol\n";
    }
    public static function FinishedErrorCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "This symbol does not compute: $symbol\n";
    }
    /*
    * State : before Sale.save()
    */
    public static function populate_gid($new_conn)
    {
        while(true)
        {
            unset($tmp_tmp_guid);
            $tmp_tmp_guid = self::uniqidReal();
            unset($tmp_guid);
            $tmp_guid = $new_conn->TABLE('SALES')->WHERE([['guid', '=', self::SQLChaine($tmp_tmp_guid)], ['email', '=', self::SQLChaine(self::$email)]])->VALUE('guid');
            if(empty($tmp_guid))
            {
                self::$guid = $tmp_tmp_guid;
                break;
            }
        }
        return(self::$guid);
    }
    public static function create($params)
    {
        self::update($params);
        return($this);
    }
    public static function save($new_conn)
    {
        /*
        * Fin de
        * la fonction.
        */
        self::$guid = self::populate_gid($new_conn);
        $new_conn->TABLE('SALES')->INSERT(array('guid' => self::SQLChaine(self::$guid), 'email' => self::SQLChaine(self::$email), 'product_id' => self::SQLChaine(self::$product_id), 'charge_id' => self::SQLChaine(self::$stripe_id), 'card_expiration' => self::$card_expiration, 'amount' => self::$amount, 'fee_amount' => self::$fee_amount, 'error' => self::SQLChaine(self::$error)));
    }
    public static function find_by($guid, $new_conn)
    {
        $tmp_array_sale = $new_conn->TABLE('SALES')->WHERE('guid', '=', self::SQLChaine($guid))->SELECT('guid', 'email', 'product_id')->FIRST();
        if(!empty($tmp_array['guid']))
        {
            /*
            * Update
            * de l'attribut
            * self::$sale
            * de Sale.
            */
            self::updateSale($tmp_array);
            return(self::$sale);
        }
        else
        {
            return(null);
        }
    }
/*
    event: process after: :charge_card
    {
        transition from : pending to :processing
            save();
        event: process after: :charge_card
    }
    event: finish
    {
        transition from : processing pending to :finished
    }
    event: fail
    {
        transition from : processing pending to :errored
    }
 */
    /*
    * Declenche apres
    * sale.save(),
    * par :process.
    */
    public static function charge_card($stripe)
    {
        try {
//            $charge = self::charges()->create([
            $charge = $stripe->charges()->create([
                'amount'        => self::amount,
                'currency'      => 'EUR',
                'source'        => self::stripe_token,
                'description'   => self::email]);
        } catch ( Cartalyst\Stripe\Exception\BadRequestException $e ) {
            // Get the status code
            $code = $e->getCode();
            // Get the error message returned by Stripe
            $message = $e->getMessage();
            // Get the error type returned by Stripe
            $type = $e->getErrorType();
            self::update_attributes(array('error' => $message));
            echo "Error Code = " . $code . "\tMessage Stripe : " . $message . "\tType = " . $type . "<br />\n";
            return(false);
            /*
            * Action
            * sur le FSM.
            */
            //    self::fail!;
        }
        /*
        * Action
        * sur le FSM.
        */
        //    event self::finish! :
        try {
//            $balance = self::balance()->find($charge->balance_transaction);
            $balance = $stripe->balance()->find($charge->balance_transaction);
        } catch ( Cartalyst\Stripe\Exception\NotFoundException $e ) {
            // Get the status code
            $code = $e->getCode();
            // Get the error message returned by Stripe
            $message = $e->getMessage();
            // Get the error type returned by Stripe
            $type = $e->getErrorType();
            self::update_attributes(array('error' => $message));
            echo "Error Code = " . $code . "\tMessage Stripe : " . $message . "\tType = " . $type . "<br />\n";
            return(false);
        }
        /*
        * Fonction
        * updatant
        * les attributs
        * de Sale.
        */
        self::update([
            'stripe_id'        => $charge.id,
            'card_expiration'    => $charge->source->expr_year . "-" . $charge->source->exp_month . "-1",
            'fee_amount'        => $balance->fee]);
        return(true);
    }
    /*
    * Pour render
    * en cas d'erreeur.
    */
    public static function first($stripe)
    {
        try {
//            self::product = self::products()->find($this>product_id);
            self::$product = $stripe->products()->find($this>product_id);
        } catch ( Cartalyst\Stripe\Exception\NotFoundException $e ) {
            // Get the status code
            $code = $e->getCode();
            // Get the error message returned by Stripe
            $message = $e->getMessage();
            // Get the error type returned by Stripe
            $type = $e->getErrorType();
            echo "Error Code = " . $code . "\tMessage Stripe : " . $message . "\tType = " . $type . "<br />\n";
            return(false);
        }
        return(true);
    }
    public static function pickup($stripe)
    {
        self::$sale = self::find_by(self::$params['guid'], self::$params['new_conn']);
        /*
        * 1 seul Product
        * dans Sale ?
        */
        if(self::$sale !== false)
        {
            try {
                self::$product = $stripe->products()->find(self::$product_id);
            } catch ( Cartalyst\Stripe\Exception\NotFoundException $e ) {
                // Get the status code
                $code = $e->getCode();
                // Get the error message returned by Stripe
                $message = $e->getMessage();
                // Get the error type returned by Stripe
                $type = $e->getErrorType();
                echo "Error Code = " . $code . "\tMessage Stripe : " . $message . "\tType = " . $type . "<br />\n";
                return(false);
            }
        }
        return(true);
    }
    /*
        $__sale = $stripe->sales()->create([
            'email'     => self::$params['stripeEmail'],
            'stripe_id'    => $__charge->id]);
        redirect_to_pickup_url($__sale->guid);
    }
    catch Exception $e {
        * The card has been declined
        * or some other errors
        * has occured.
    $__error = $e;
}
    }
    */
}
$params = array('amount' => 10, 'card_expiration' => date('Y-m-d H:i:s', time()));
$new_conn = new Database("");
$params['new_conn'] = $new_conn;
$sale = Sale::init($params);
?>
 
WRInaute accro
Problème résolu.

J'avais oublié d'adapter le config.yml pour y inclure Sale.php

Mais le job s'exécute 6 ou 7 fois, probablement du au fait que la fonction charge_card() rend false.

Et pour cause : Je fais des tests sans transaction ( réelle ni test ) avec Stripe .

Je vais investiguer pour savoir si un job dont le perform() rend false, est répétitif ou non.

Respectueusement.


PHP:
<?php
require    __DIR__ . '/SalesController.php';
require __DIR__ . '/../../../PHP_Resque/vendor/autoload.php';
require    __DIR__ . '/StripeFunctions.php';
class SaleWorker
{
    public function setUp()
    {
        return(true);
    }
    public function tearDown()
    {
        return(true);
    }
    public function perform($args)
    {
        echo "\t\tDebut Perform().\n";
        if(Sale::save() === false)
        {
            return(false);
        }
        echo "\t\tMilieu Perform().\n";
        if(Sale::charge_card() === false)
        {
            return(false);
        }
        echo "\t\tFin Perform().\n";
        return(true);
    }
}
class Sale extends SalesController
{
    use StripeFunctions;
    /******************************************************************************************************************
    Classification des events de la FSM :
    ( quel statut de before_create ? )
    :process    ->    transition from :pending to :processing      -> :after    ->    charge_card()
    :finish
    ou :
    :fail
    Sequencement des fonctions :
    authenticate_user() -> populate_guid() -> sale.create() -> :process -> sale.save() -> sale.charge_card() ->
    before action : first ou create : authenticate_user();
    ******************************************************************************************************************/
    /*
    1 Sale a 1 ou + Product.
    Parametres de Sale :
    $state, $stripe_id, $stripe_token, $card_expiration, $error, $fee_amount, $amount, $email, $guid, $ref_products, $others
    */
    public static $Process        = null;
    public static $ProcessId    = null;
    public static $status        = null;
    public static $guid        = null;
    public static $sale        = array();
    public $new_conn        = array();
    public $stripe            = array();
    public static $sale_state    = null;    /* Valeurs : "before_first_action", "before_create", "process", "finished", "fail" */
    public $state            = null;
    public static $stripe_id    = null;
    public static $stripe_token    = null;
    public static $card_expiration    = null;
    public static $params        = null;
    public static $email        = '';
    public static $amount        = 0;
    public static $fee_amount    = 0;
    public static $error        = null;
    public static $product_id    = null;
    public static $product        = null;
    public static function init($params)
    {
        parent::init($params);
        self::$sale_state    = "before_first_action";
        self::$params    = $params;
        self::$params['new_conn'] = new Database("");
        self::$params['stripe'] = new StripeFSM();
        self::update(self::$params);
        self::updateSale(self::$params);
        parent::createFSM();
        self::$email = self::uniqidReal();
        /**
        *
        Resque::push(function($job) {
            echo 'This is a inline job #'.$job->getId().'!';
    });
    *
        **/
        return;
    }
    public static function StartCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "TO_PENDING Transition1\n";
    }
    public static function PendingCallback($symbol, &$payload, $currentState, $nextState)
    {
        self::$Process = Resque::push('SaleWorker', self::$params);
                self::$ProcessId = self::$Process->getId();
                echo "\t\tProcessId = " . self::$ProcessId . "\n";
                $job = Resque\Job::load(self::$ProcessId);
                self::$status = $job->getStatus();
               switch (self::$status) {
                case Resque\Job::STATUS_WAITING :
                        echo "Job is still queued.\n";
                        break;
                case Resque\Job::STATUS_DELAYED :
                        echo "Job is delayed.\n";
                        break;
                case Resque\Job::STATUS_RUNNING :
                        echo "Job is currently running.\n";
                        break;
                case Resque\Job::STATUS_COMPLETE :
                        echo "Job is complete.\n";
                        break;
                case Resque\Job::STATUS_CANCELLED :
                        echo "Job has been cancelled.\n";
                        break;
                case Resque\Job::STATUS_FAILED :
                        echo "Job has failed.\n";
                        break;
                case false :
                        echo "Failed to fetch the status - is the id valid?\n";
                        break;
                default :
                        echo "Status unknown.\n";
                        break;
                }
        echo "TO_PROCESSING Transition2\n";
    }
    public static function ProcessingCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "TO_FINISHED Transition3\n";
    }
    public static function StartErrorCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "This symbol does not compute: $symbol\n";
    }
    public static function PendingErrorCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "This symbol does not compute: $symbol\n";
    }
    public static function ProcessingErrorCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "This symbol does not compute: $symbol\n";
    }
    public static function FinishedErrorCallback($symbol, &$payload, $currentState, $nextState)
    {
        echo "This symbol does not compute: $symbol\n";
    }
    /*
    * State : before Sale.save()
    */
    public static function populate_gid()
    {
        $new_conn = self::$params['new_conn'];
        while(true)
        {
            unset($tmp_tmp_guid);
            $tmp_tmp_guid = self::uniqidReal();
            unset($tmp_guid);
            $tmp_guid = $new_conn->TABLE('SALES')->WHERE([['guid', '=', self::SQLChaine($tmp_tmp_guid)], ['email', '=', self::SQLChaine(self::$email)]])->VALUE('guid');
            if(empty($tmp_guid))
            {
                self::$guid = $tmp_tmp_guid;
                break;
            }
        }
        return(self::$guid);
    }
    public static function create($params)
    {
        self::update($params);
        return($this);
    }
    public static function save()
    {
        $new_conn = self::$params['new_conn'];
        /*
        * Fin de
        * la fonction.
        */
        self::$guid = self::populate_gid();
        $new_conn->TABLE('SALES')->INSERT(array('guid' => self::SQLChaine(self::$guid), 'email' => self::SQLChaine(self::$email), 'product_id' => self::SQLChaine(self::$product_id), 'charge_id' => self::SQLChaine(self::$stripe_id), 'card_expiration' => self::$card_expiration, 'amount' => self::$amount, 'fee_amount' => self::$fee_amount, 'error' => self::SQLChaine(self::$error)));
    }
    public static function find_by($guid, $new_conn)
    {
        $tmp_array_sale = $new_conn->TABLE('SALES')->WHERE('guid', '=', self::SQLChaine($guid))->SELECT('guid', 'email', 'product_id')->FIRST();
        if(!empty($tmp_array['guid']))
        {
            /*
            * Update
            * de l'attribut
            * self::$sale
            * de Sale.
            */
            self::updateSale($tmp_array);
            return(self::$sale);
        }
        else
        {
            return(null);
        }
    }
/*
    event: process after: :charge_card
    {
        transition from : pending to :processing
            save();
        event: process after: :charge_card
    }
    event: finish
    {
        transition from : processing pending to :finished
    }
    event: fail
    {
        transition from : processing pending to :errored
    }
 */
    /*
    * Declenche apres
    * sale.save(),
    * par :process.
    */
    public static function charge_card()
    {
        $stripe = self::$params['stripe'];
        try {
//            $charge = self::charges()->create([
            $charge = $stripe->charges()->create([
                'amount'        => self::$amount,
                'currency'      => 'EUR',
                'source'        => self::$stripe_token,
                'description'   => self::$email]);
        } catch ( Cartalyst\Stripe\Exception\BadRequestException $e ) {
            // Get the status code
            $code = $e->getCode();
            // Get the error message returned by Stripe
            $message = $e->getMessage();
            // Get the error type returned by Stripe
            $type = $e->getErrorType();
            self::update_attributes(array('error' => $message));
            echo "Error Code = " . $code . "\tMessage Stripe : " . $message . "\tType = " . $type . "<br />\n";
            return(false);
            /*
            * Action
            * sur le FSM.
            */
            //    self::fail!;
        }
        /*
        * Action
        * sur le FSM.
        */
        //    event self::finish! :
        try {
//            $balance = self::balance()->find($charge->balance_transaction);
            $balance = $stripe->balance()->find($charge->balance_transaction);
        } catch ( Cartalyst\Stripe\Exception\NotFoundException $e ) {
            // Get the status code
            $code = $e->getCode();
            // Get the error message returned by Stripe
            $message = $e->getMessage();
            // Get the error type returned by Stripe
            $type = $e->getErrorType();
            self::update_attributes(array('error' => $message));
            echo "Error Code = " . $code . "\tMessage Stripe : " . $message . "\tType = " . $type . "<br />\n";
            return(false);
        }
        /*
        * Fonction
        * updatant
        * les attributs
        * de Sale.
        */
        self::update([
            'stripe_id'        => $charge.id,
            'card_expiration'    => $charge->source->expr_year . "-" . $charge->source->exp_month . "-1",
            'fee_amount'        => $balance->fee]);
        return(true);
    }
    /*
    * Pour render
    * en cas d'erreeur.
    */
    public static function first($stripe)
    {
        try {
//            self::product = self::products()->find($this>product_id);
            self::$product = $stripe->products()->find($this>product_id);
        } catch ( Cartalyst\Stripe\Exception\NotFoundException $e ) {
            // Get the status code
            $code = $e->getCode();
            // Get the error message returned by Stripe
            $message = $e->getMessage();
            // Get the error type returned by Stripe
            $type = $e->getErrorType();
            echo "Error Code = " . $code . "\tMessage Stripe : " . $message . "\tType = " . $type . "<br />\n";
            return(false);
        }
        return(true);
    }
    public static function pickup($stripe)
    {
        self::$sale = self::find_by(self::$params['guid']);
        /*
        * 1 seul Product
        * dans Sale ?
        */
        if(self::$sale !== false)
        {
            try {
                self::$product = $stripe->products()->find(self::$product_id);
            } catch ( Cartalyst\Stripe\Exception\NotFoundException $e ) {
                // Get the status code
                $code = $e->getCode();
                // Get the error message returned by Stripe
                $message = $e->getMessage();
                // Get the error type returned by Stripe
                $type = $e->getErrorType();
                echo "Error Code = " . $code . "\tMessage Stripe : " . $message . "\tType = " . $type . "<br />\n";
                return(false);
            }
        }
        return(true);
    }
    /*
        $__sale = $stripe->sales()->create([
            'email'     => self::$params['stripeEmail'],
            'stripe_id'    => $__charge->id]);
        redirect_to_pickup_url($__sale->guid);
    }
    catch Exception $e {
        * The card has been declined
        * or some other errors
        * has occured.
    $__error = $e;
}
    }
    */
}
$params = array('amount' => 10, 'card_expiration' => date('Y-m-d H:i:s', time()));
$sale = Sale::init($params);
?>
 
WRInaute accro
Bonbon

Effectivement, PHP_Resque de mjphaynes répète un job quand il échoue.

Ouf de ouf... je n'ai plus qu'à voir l'algorithmique complète de ce module de paiement, et puis le mettre au point.

Les moyens... logistiques( si j'ose dire ), sont corrects, y a plus qu'à. ;)

Et... avec mon ORM ;)

Bien amicalement.
 
Discussions similaires
Haut