PHP code example of odesk / phystrix

1. Go to this page and download the library: Download odesk/phystrix library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

odesk / phystrix example snippets


use Odesk\Phystrix\AbstractCommand;

/**
 * All commands must extends Phystrix's AbstractCommand
 */
class MyCommand extends AbstractCommand
{
    protected $name;

    public function __construct($name)
    {
        $this->name = $name;
    }

    /**
     * This function is called internally by Phystrix, only if the request is allowed
     *
     * @return mixed
     */
    protected function run()
    {
        return 'Hello ' . $this->name;
    }
}

$myCommand = $phystrix->getCommand('MyCommand', 'Alex'); // 'Alex' is passed to MyCommand's constructor
$result = $myCommand->execute();

use Zend\Config\Config;
use Odesk\Phystrix\ApcStateStorage;
use Odesk\Phystrix\CircuitBreakerFactory;
use Odesk\Phystrix\CommandMetricsFactory;
use Odesk\Phystrix\CommandFactory;

$config = new Config(ctory(
    $config, new \Zend\Di\ServiceLocator(), $circuitBreakerFactory, $commandMetricsFactory,
    new \Odesk\Phystrix\RequestCache(), new \Odesk\Phystrix\RequestLog()
);

return array(
    'default' => array( // Default command configuration
        'fallback' => array(
            // Whether fallback logic of the phystrix command is enabled
            'enabled' => true,
        ),
        'circuitBreaker' => array(
            // Whether circuit breaker is enabled, if not Phystrix will always allow a request
            'enabled' => true,
            // How many failed request it might be before we open the circuit (disallow consecutive requests)
            'errorThresholdPercentage' => 50,
            // If true, the circuit breaker will always be open regardless the metrics
            'forceOpen' => false,
            // If true, the circuit breaker will always be closed, allowing all requests, regardless the metrics
            'forceClosed' => false,
            // How many requests we need minimally before we can start making decisions about service stability
            'requestVolumeThreshold' => 10,
            // For how long to wait before attempting to access a failing service
            'sleepWindowInMilliseconds' => 5000,
        ),
        'metrics' => array(
            // This is for caching metrics so they are not recalculated more often than needed
            'healthSnapshotIntervalInMilliseconds' => 1000,
            // The period of time within which we the stats are collected
            'rollingStatisticalWindowInMilliseconds' => 1000,
            // The more buckets the more precise and actual the stats and slower the calculation.
            'rollingStatisticalWindowBuckets' => 10,
        ),
        'requestCache' => array(
            // Request cache, if enabled and a command has getCacheKey implemented
            // caches results within current http request
            'enabled' => true,
        ),
        'requestLog' => array(
            // Request log collects all commands executed within current http request
            'enabled' => false,
        ),
    ),
    'MyCommand' => array( // Command specific configuration
        'fallback' => array(
            'enabled' => false
        )
    )
);

    /**
     * This function defines the command key to use for this command
     *
     * @return string
     */
    protected function getCommandKey()
    {
        return 'CustomCommandKey';
    }

use Zend\Config\Config;
$myCommand = $phystrix->getCommand('MyCommand', 'Alex');
$myCommand->setConfig(new Config(array('requestCache' => array('enabled' => false))));
$result = $myCommand->execute();

class GetAvatarUrlCommand extends AbstractCommand
{
    protected $user;

    public function __construct($user)
    {
        $this->user = $user;
    }

    protected function run()
    {
        $remoteAvatarService = $this->serviceLocator->get('avatarService');
        return $remoteAvatarService->getUrlByUser($this->user);
    }

    /**
     * When __run__ fails for some reason, or when Phystrix doesn't allow the request in the first place,
     * this function result will be returned instead
     *
     * @return string
     */
    protected function getFallback()
    {
        // we failed getting user's picture, so showing a generic no-photo placeholder instead.
        return 'http://example/avatars/no-photo.jpg';
    }
}

    protected function getCacheKey()
    {
        return 'cache_' . $this->user;
    }

    'MyCommand' => array(
        'fallback' => array(
            'enabled' => false
        ),
        'timeout' => 2000, // milliseconds
    )

    protected function run()
    {
        $remoteAvatarService = $this->serviceLocator->get('avatarService');
        return $remoteAvatarService->getUrlByUser($this->user);
    }

    /**
     * Custom preparation logic, preceding command execution
     */
    protected function prepare()
    {
        $remoteAvatarService = $this->serviceLocator->get('avatarService');
        if ($this->config->__isset('timeout')) {
            // if the timeout is exceeded an exception will be thrown
            $remoteAvatarService->setTimeout($this->config->get('timeout'));
        }
    }

$serviceLocator = \Zend\Di\ServiceLocator();
$googleApiRemoteService = new GoogleApi(...);
$serviceLocator->set('googleApi', $googleApiRemoteService);

$phystrix = new CommandFactory(
    $config, $serviceLocator, $circuitBreakerFactory,
    $commandMetricsFactory, new \Odesk\Phystrix\RequestCache()
);

    protected function run()
    {
        $googleApi = $this->serviceLocator->get('googleApi');
        return $googleApi->fetchAllEmail();
    }

/** @var RequestLog $requestLog */
$commands = $requestLog->getExecutedCommands();

$command->getExecutionTimeInMilliseconds();

$command->getExecutionEvents();