A unified front-end for different queuing backends. Includes a REST server, CLI interface and daemon runners.

Overview

PHP-Queue

Gitter

A unified front-end for different queuing backends. Includes a REST server, CLI interface and daemon runners.

Build Status

Why PHP-Queue?

Implementing a queueing system (eg. Beanstalk, Amazon SQS, RabbitMQ) for your application can be painful:

  • Which one is most efficient? Performant?
  • Learning curve to effectively implement the queue backend & the libraries.
  • Time taken to develop the application codes.
  • Vendor locked in, making it impossible to switch.
  • Requires massive code change (ie. not flexible) when use case for the queue changes.

PHP-Queue hopes to serve as an abstract layer between your application code and the implementation of the queue.

Benefits

  • Job Queue is Backend agnostic

    Just refer to the queue by name, what it runs on is independent of the application code. Your code just asks for the next item in the PHPQueue\JobQueue, and you'll get a PHPQueue\Job object with the data and jobId.

  • Flexible Job Queue implementation

    You can decide whether each PHPQueue\JobQueue only carries 1 type of work or multiple types of target workers. You control the retrieval of the job data from the Queue Backend and how it is instantiated as a PHPQueue\Job object. Each PHPQueue\Job object carries information on which workers it is targeted for.

  • Independent Workers

    Workers are independent of Job Queues. All it needs to worry about is processing the input data and return the resulting data. The queue despatcher will handle the rest. Workers will also be chainable.

  • Powerful

    The framework is deliberately open-ended and can be adapted to your implementation. It doesn't get in the way of your queue system.

    We've build a simple REST server to let you post job data to your queue easily. We also included a CLI interface for adding and triggering workers. All of which you can sub-class and overwrite.

    You can also include our core library files into your application and do some powerful heavy lifting.

    Several backend drivers are bundled:

    • Memcache
    • Redis
    • MongoDB
    • CSV These can be used as the primary job queue server, or for abstract FIFO or key-value data access.

Installation

Installing via Composer

Composer is a dependency management tool for PHP that allows you to declare the dependencies your project needs and installs them into your project. In order to use the PHP-Queue through Composer, you must do the following:

  1. Add "coderkungfu/php-queue" as a dependency in your project's composer.json file. Visit the Packagist page for more details.

  2. Download and install Composer.

curl -s "http://getcomposer.org/installer" | php
  1. Install your dependencies.
php composer.phar install
  1. All the dependencies should be downloaded into a vendor folder.

  2. Require Composer's autoloader.

<?php
require_once '/path/to/vendor/autoload.php';
?>

Getting Started

You can have a look at the Demo App inside .\vendor\coderkungfu\php-queue\src\demo\ folder for a recommended folder structure.

  • htdocs folder
    • .htaccess
    • index.php
  • queues folder
    • <QueueNameInCamelCase>Queue.php
  • workers folder
    • <WorkerNameInCamelCase>Worker.php
  • runners folder
  • cli.php file
  • config.php file

I would also recommend putting the autoloader statement and your app configs inside a separate config.php file.

Recommended config.php file content:

<?php
require_once '/path/to/vendor/autoload.php';
PHPQueue\Base::$queue_path = __DIR__ . '/queues/';
PHPQueue\Base::$worker_path = __DIR__ . '/workers/';
?>

Altenative config.php file:

You can also declare your application's namespace for loading the Queues and Workers.

<?php
require_once '/path/to/vendor/autoload.php';
PHPQueue\Base::$queue_namespace = '\MyFabulousApp\Queues';
PHPQueue\Base::$worker_namespace = '\MyFabulousApp\Workers';
?>

PHP-Queue will attempt to instantiate the PHPQueue\JobQueue and PHPQueue\Worker classes using your namespace - appended with the queue/worker name. (ie. \MyFabulousApp\Queues\Facebook).

It might be advisable to use Composer's Custom Autoloader for this.

Note:
If you declared PHPQueue\Base::$queue_path and/or PHPQueue\Base::$worker_path together with the namespace, the files will be loaded with require_once from those folder path AND instantiated with the namespaced class names.

REST Server

The default REST server can be used to interface directly with the queues and workers.

Copy the htdocs folder in the Demo App into your installation. The index.php calls the \PHPQueue\REST::defaultRoutes() method - which prepares an instance of the Respect\Rest REST server. You might need to modify the path of config.php within the index.php file.

Recomended installation: use a new virtual host and map the htdocs as the webroot.

  1. Add new job.
# Form post
curl -XPOST http://localhost/<QueueName>/ -d "var1=foo&var2=bar"
# JSON post
curl -XPOST http://localhost/<QueueName>/ -H "Content-Type: application/json" -d '{"var1":"foo","var2":"bar"}'
  1. Trigger next job.
curl -XPUT http://localhost/<QueueName>/

Read the full documentation on Respect\Rest to further customize to your application needs (eg. Basic Auth).

Command Line Interface (CLI)

Copy the cli.php file from the Demo App into your installation. This file implements the \PHPQueue\Cli class. You might need to modify the path of config.php within the cli.php file.

  1. Add new job.
$ php cli.php <QueueName> add --data '{"boo":"bar","foo":"car"}'
  1. Trigger next job.
$ php cli.php <QueueName> work

You can extend the PHPQueue\Cli class to customize your own CLI batch jobs (eg. import data from a MySQL DB into a queue).

Runners

You can read more about the Runners here.

Interfaces

The queue backends will support one or more of these interfaces:

  • AtomicReadBuffer

This is the recommended way to consume messages. AtomicReadBuffer provides the popAtomic($callback) interface, which rolls back the popped record if the callback returns by exception. For example: $queue = new PHPQueue\Backend\PDO($options);

$queue->popAtomic(function ($message) use ($processor) {
    $processor->churn($message);
});

The message will only be popped if churn() returns successfully.

  • FifoQueueStore

A first in first out queue accessed by push and pop.


License

This software is released under the MIT License.

Copyright (C) 2012 Michael Cheng Chi Mun

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Comments
  • Backend function signatures are not compatible

    Backend function signatures are not compatible

    For example, Memcache::add() takes arguments (key, data, expiry), but Base::add() and IronMQ::add() start with the $data argument. It seems like the right thing to do is change the signature in Memcache::add to start with $data.

    opened by adamwight 9
  • Adding jobs dynamically not working

    Adding jobs dynamically not working

    Hello,

    I've tested your script but seems that once you run php SimpleRunner.php all jobs added after that are not updated.

    I've tried also to run BeanstalkSampleDaemon but there are several errors like:

    Fatal error: Class 'Pheanstalk\Pheanstalk' not found

    opened by carcabot 8
  • Allow use of Monolog 2.x (as well as 1.x)

    Allow use of Monolog 2.x (as well as 1.x)

    No changes needed to the Logger class itself, as the StreamHandler constructor is compatible in 2.x. Usages of non-PSR-standard e.g. Logger->addInfo() methods are replaced with PSR-standard e.g. Logger->info() calls, as both exist in 1.x and the former are removed in Monolog 2.

    See https://github.com/Seldaek/monolog/blob/main/UPGRADE.md

    opened by ejegg 4
  • Added support for AWS PHP SDK version 2

    Added support for AWS PHP SDK version 2

    I noticed Amazon released version 2 of their PHP SDK a while back, so I added support for it.

    The changes include:

    • Moving Respect/Rest to the "suggest" section in composer.json, since some people may not want to use the REST server, or wish to implement it themselves
    • Added the PEAR repository definition, which is required for microsoft/windowsazure
    • Bumped the Monolog version for compatibility with newer Symfony2 libraries (the new AWS SDK depends on the Symfony2 event dispatcher and Guzzle)
    • Added AmazonSQSV2 and AmazonS3V2 Backend classes, which use the new library functions
    • Added Base::setConnection(), which enables dependency injection (e.g. someone might want to pass an existing connection object to a backend instance)
    • Added tests for the new classes and functions

    What do you think? I thought of simply replacing the AWS classes, but some people might want to stay with the old SDK. Maybe do it in a different version branch?

    opened by gigablah 4
  • Automatic db diff generation

    Automatic db diff generation

    Hey, excellent project and all, but you should be aware of the existence of this tool:

    https://bitbucket.org/idler/mmp/wiki/Home

    how about incorporating the two!

    Edit: the project page is now at

    https://github.com/idler/MMP/

    opened by raveren 4
  • Delay Queue

    Delay Queue

    Hi,

    Is there any possibility to delay a queued job ?

    for example this job must be delayed 5 minutes.

     $obj = array(
                    'Schedule' => time() + (5 * 60)
                );
    $queue->addJob($obj);
    
    

    If you have other idea will be great. Thanks.

    opened by carcabot 3
  • Consolidate return-value vs exception throwing

    Consolidate return-value vs exception throwing

    There is some tension between the queue backend functions which return true and throw exceptions. If there is no way to return false, then calling code will include redundant error handling for no good reason.

    However, voiding the return value will probably break existing code. We can leave the "return true" until this usage is deprecated...

    Do you agree that we should throw a JobNotFound exception whenever get($key) or pop() fails to find a message?

    opened by adamwight 2
  • AUTOMATED: WhiteSpace Removal

    AUTOMATED: WhiteSpace Removal

    This is an automated request to remove excessive whitespace from source code. You can find more about this project and opt-out at whitespacestrippers.com

    opened by WhiteSpace-Strippers 2
  • Replace file_exists() with is_file()

    Replace file_exists() with is_file()

    php-queue\src\PHPQueue\Base.php Line 48 - if (file_exists($classFile)) Line 175 - if (file_exists($classFile))

    php-queue\src\PHPQueue\Backend\CSV.php Line 29 - if ( !file_exists($this->file_path) )

    opened by Yahasana 2
  • Upstreaming the rest of WMF's changes

    Upstreaming the rest of WMF's changes

    • Removes our non-queuey KeyValueStore and IndexedFifoQueueStore interfaces These were only supported by certain backends, and support in those was buggy (i.e. delete in ActiveMQ only works if the key is within a certain distance of the top)
    • Adds an AtomicReadBuffer interface Useful for at-least-once processing. Gets a value from the queue and only pops it off once a callback has completed successfully
    • Bugfixes for Predis and PDO backends

    Please let me know if you'd like me to break up this PR!

    opened by ejegg 1
  • Priority, Delay , TTR Job

    Priority, Delay , TTR Job

    Hi,

    First of all thanks to author and contributors for this useful script.

    I enjoyed it a lot but I also wanted to have a delay feature so i decided to contribute a little to this awesome script adding this feature.

        DEFAULT_PRIORITY = 1024; // most urgent: 0, least urgent: 4294967295
        DEFAULT_DELAY = 0; // no delay
        DEFAULT_TTR = 60; // 1 minute
    

    Example of using:

    $queue = new MyQueue();
    $test = array('test'=>'test2');
    $queue->addJob($test, 1024, 60, 60);
    
    opened by carcabot 1
  • Consider using queue interprop as abstraction for queues

    Consider using queue interprop as abstraction for queues

    Hello!

    Please look at https://github.com/queue-interop/queue-interop project. Using interfaces from it allows us reuse some implementations like enqueue, which supports a lot of transports. You can outsource some code

    opened by makasim 1
  • Base namespaces not working properly

    Base namespaces not working properly

    Hey, so I have structure like this

    PHPQueue\Base::$queue_namespace = 'App\Queue\Queues'; PHPQueue\Base::$worker_namespace = 'App\Queue\Workers';

    ├── Queues │   ├── SampleQueue.php │   └── logs │   └── results.log ├── Runners │   └── SampleRunner.php └── Workers └── SampleWorker.php

    when running trought CLI

    Adding Job... Fatal error: Class 'App\Queue\Queues\Sample' not found in ...

    So :QueueNameInCamelCase:Queue.php is not working for namespaces

    opened by Horki 1
  • error on composer dev dependencies

    error on composer dev dependencies

      Problem 1
        - Installation request for microsoft/windowsazure dev-master -> satisfiable by microsoft/windowsazure[dev-master].
        - microsoft/windowsazure dev-master requires pear-pear2.php.net/http_request2 * -> no matching package found.
    
    
    opened by bshaffer 3
  • Seeking co-committers.

    Seeking co-committers.

    Hi,

    I have been really busy with my career these few years. Haven't been doing a good job of keeping this library up to date.

    I'm hoping to open up commit access to other developers who might want to help take this project further. Do respond here to email me at [email protected] to discuss further.

    Thanks!

    opened by miccheng 1
  • Tighten up configuration

    Tighten up configuration

    Interfaces\Config is unused. Tests and demo applications should be locally configured with a single file config.yaml.example, rather than in code.

    I don't know what the config data should look like. It would be nice to include backend dependency injection, as well as defaults for each backend, but this seems like an overly complicated configuration file, it would look something like:

    stomp:
        uri: tcp://host.localhost.net:61613
        read_timeout: 10
    
    queues:
        test_stomp:
            backend: Stomp
    
    opened by adamwight 2
  • Feature request: Move job logic out of Backend\Base class

    Feature request: Move job logic out of Backend\Base class

    I like the idea of keeping before & after hooks on every action in the Base class, but what do you think about decoupling the job tracking (last_job_id and open_items) into a new class? Or even isolating all job queue logic in a new component? Plain old queue stuff is a useful service to provide in a library, on its own!

    Also, I don't understand how the before and after hooks would be overridden. Maybe there should be an example in the demo/ dir? I ask because I'm thinking about removing or refactoring these functions, if they aren't being used.

    opened by adamwight 1
Laravel Cron Scheduling - The ability to run the Laravel task scheduler using different crons

Laravel Cron Scheduling Laravel Task Scheduling is a great way to manage the cron. But the documentation contains the following warning: By default, m

Sergey Zhidkov 4 Sep 9, 2022
Manage your Laravel Task Scheduling in a friendly interface and save schedules to the database.

Documentation This librarian creates a route(default: /schedule) in your application where it is possible to manage which schedules will be executed a

Roberson Faria 256 Dec 21, 2022
The power of webpack, distilled for the rest of us.

Introduction Laravel Mix provides a clean, fluent API for defining basic webpack build steps for your applications. Mix supports several common CSS an

Jeffrey Way 5.2k Jan 6, 2023
xcron - the souped up, modernized cron/Task Scheduler for Windows, Mac OSX, Linux, and FreeBSD server and desktop operating systems.

xcron is the souped up, modernized cron/Task Scheduler for Windows, Mac OSX, Linux, and FreeBSD server and desktop operating systems. MIT or LGPL.

CubicleSoft 7 Nov 30, 2022
Modern and simple PHP task runner inspired by Gulp and Rake aimed to automate common tasks

RoboTask Modern and simple PHP task runner inspired by Gulp and Rake aimed to automate common tasks: writing cross-platform scripts processing assets

Consolidation 2.6k Jan 3, 2023
Manage all your cron jobs without modifying crontab. Handles locking, logging, error emails, and more.

Jobby, a PHP cron job manager Install the master jobby cron job, and it will manage all your offline tasks. Add jobs without modifying crontab. Jobby

null 1k Dec 25, 2022
PHP port of resque (Workers and Queueing)

php-resque: PHP Resque Worker (and Enqueue) Resque is a Redis-backed library for creating background jobs, placing those jobs on one or more queues, a

Chris Boulton 3.5k Jan 5, 2023
A versatile and lightweight PHP task runner, designed with simplicity in mind.

Blend A versatile and lightweight PHP task runner, designed with simplicity in mind. Table of Contents About Blend Installation Config Examples API Ch

Marwan Al-Soltany 42 Sep 29, 2022
Schedule and unschedule eloquent models elegantly without cron jobs

Laravel Schedulable Schedule and Unschedule any eloquent model elegantly without cron job. Salient Features: Turn any Eloquent Model into a schedulabl

Neelkanth Kaushik 103 Dec 7, 2022
A course database lookup tool and schedule building web application for use at Rochester Institute of Technology.

CSH ScheduleMaker A course database lookup tool and schedule building web application for use at Rochester Institute of Technology. Built, maintained

Computer Science House 55 Nov 8, 2022
A unified front-end for different queuing backends. Includes a REST server, CLI interface and daemon runners.

PHP-Queue A unified front-end for different queuing backends. Includes a REST server, CLI interface and daemon runners. Why PHP-Queue? Implementing a

CoderKungfu 646 Dec 30, 2022
PHP-Queue: A unified front-end for different queuing backends. Includes a REST server, CLI interface and daemon runners.

A unified front-end for different queuing backends. Includes a REST server, CLI interface and daemon runners. Why PHP-Queue? Implementing a

CoderKungfu 646 Dec 30, 2022
Laravel 5 boilerplate with front-end and back-end support

Laravel 5 Boilerplate with Skeleton framework Skeleton (as of now) Laravel 5 framework application. Application includes and/or are currently being us

Robert Hurd 40 Sep 17, 2021
This is a project that was created for the main purpose of practising front end technology(HTML, CSS and Java-Script) with a litle addition of back-end technology.

This is a project that was created for the main purpose of practising front end technology(HTML, CSS and Java-Script) with a litle addition of back-end technology. This is a restaurant website which is to offer services such as ordering goods through sending of emails, viewing of any order, signing-in/up for customer's who want to order food, and much more, with also some live features like dates of the day alongside opening and closing working ours. So let's jump right into it.

null 1 Nov 26, 2021
A PHP notebook application build with PHP Symfony as back-end API and VueJS/Vuetify front-end.

PHPersonal Notes ?? - BETA RELEASE PHPersonal notes is an application to store your personal notes! PHPersonalnotes is build with Symfony/VueJS/Vuetif

Robert van Lienden 3 Feb 22, 2022
Faculty Management System (FMS) Built with Laravel 9 in Back-end and React , Redux in Front-end API's

Final Project Faculty Management System (FMS) as final project for faculty of Copmuter Science, Kandahar University, 2021 Faculty Management System (F

Shahghasi Adil 7 Jun 21, 2022
Hamtaro - the new web framework for front-end / back-end development using Php and Javascript.

Hamtaro framework About Technologies Controllers Components Commands Front-end development Getting Started About Hamtaro is the new web framework for

Phil'dy Jocelyn Belcou 3 May 14, 2022
18Laravel ReactJS Package to simplify sending data from Laravel back-end to front-end built to Facebook ReactJS.

Laravel ReactJS This is a package that we wrote to use on our Laravel applications that use React from Facebook. Our goal is deal with the SEO problem

Cohros 28 Feb 10, 2022
Tcc realizado na Etec de Guaianazes (2021),onde eu fui o back-end e Vinicius de Almeida foi o front-end.

TCC-Facilita+ Todos os arquivos do projeto de TCC (Facilita+) da Etec de Guaianases realizado em 2021 1° Para utilizar os arquivos,primeiro será nesce

Helder Davidson Rodrigues Alvarenga 0 Jun 15, 2022
CherryStar is a compilation of technologies that you must know to work as back-end or front-end developer.

CherryStar - Study case, starting with recent technologies CherryStar is a compilation of technologies that you must know to work as back-end or front

Renan R. Murussi 8 Sep 8, 2022