Introduction
Achtung! Documentation is under active construction! Consider making a contribution.
PHPDaemon — asynchronous framework You can built very fast applications, web-services and more on top of it. Out-of-box it provides a wide range of network servers such as FastCGI, HTTP, CGI, FlashPolicy, Telnet, WebSocket; clients like MySQL, Redis, MongoDB, PostgreSQL, Memcached, IRC, XMPP, and others. Network programming became very simple. Middle developer can implement, e.g., full-featured IRC-bot in a hour.
- Official web-site daemon.io.
- GitHub repository github.com/kakserpom/phpdaemon.
- Discussion: Google Groups.
- Issue tracker
Usage of this documentation ← Introduction
As you may see, whole documentation is placed on one page, so feel free to use standard search within the page (hotkey is Ctrl
+ F
or Cmd
+ F
)
Hotkeys ← Usage of this documentation ← Introduction
Ctrl
+↑
— previous section at the current levelCtrl
+↓
— next section at the current levelCtrl
+→
— one level downCtrl
+←
— one level up
Installation
Requirements ← Installation
PHP
version not under 5.6;- Modules
posix
,pcntl
,socket
,shmop
; libevent 2
;pecl-event
not under 1.6.1;
It's recommended to install these non-mandatory modules:
pecl-eio
for non-blocking filesystem I/O;pecl-inotify
for monitoring of changes in filesystem.
Source code ← Installation
You may clone the repository
$ git clone https://github.com/kakserpom/phpdaemon.git
Or download current version as an archive
$ wget https://github.com/kakserpom/phpdaemon/archive/master.zip
Then install mandatory PHP modules
$ pecl install event eio inotify
Composer ← Installation
Add a section into yours composer.json
"require" : {
"kakserpom/phpdaemon" : "dev-master"
}
Futhermore information about the package is located at packagist.org.
CentOS/RedHat ← Installation
First of all you should install related utilities.
$ sudo yum install -y git gcc openssl-devel libevent
To install latest PHP. you should add the Remi and the Epel repositories, because standard package may contain outdated version.
For RHEL/CentOS 6.4-6.0 32 Bit.
sudo rpm -Uvh http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
sudo rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
For RHEL/CentOS 6.4-6.0 64 Bit.
sudo rpm -Uvh http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
sudo rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-6.rpm
#Installing PHP.
sudo yum --enablerepo=remi,remi-test install -y php-cli php-devel php-pear php-process
#Then installing PHP modules.
sudo -i
pecl install event eio
#Modules `event` and `eio` require module `sockets`.
#In RedHat/CentOS, configuration files load up in alphabetic order, so name them `z-event.ini` and `z-eio.ini` accordingly.
echo "extension=event.so" > /etc/php.d/z-event.ini
echo "extension=eio.so" > /etc/php.d/z-eio.ini
exit #out of sudo
Define date.timezone
in /etc/php.ini.
#Prepare a folder for PHPDaemon.
sudo mkdir /opt/phpdaemon
sudo chown [your user]:[your group] /opt/phpdaemon
cd /opt/phpdaemon
#Installing PHPDaemon.
cd /opt/phpdaemon
git clone https://github.com/kakserpom/phpdaemon.git ./
#Copying configuration file from sample:
cp /opt/phpdaemon/conf/phpd.conf.example /opt/phpdaemon/conf/phpd.conf
#Creating a link for phpd
ln -s /opt/phpdaemon/bin/phpd /usr/bin/phpd
Then run the thing:
$ sudo phpd start --verbose-tty=1
Option --verbose-tty=1
turns on logging into STDOUT
If you see something like this:
[PHPD] Loaded config file: '/opt/phpdaemon/conf/phpd.conf'
[PHPD] Loaded config file: 'conf/conf.d/ExampleJabberBot.conf'
[PHPD] Loaded config file: 'conf/conf.d/FastCGI.conf'
[PHPD] Loaded config file: 'conf/conf.d/FlashpolicyServer.conf'
[PHPD] Loaded config file: 'conf/conf.d/HTTPServer.conf'
[PHPD] Loaded config file: 'conf/conf.d/IdentServer.conf'
[PHPD] Loaded config file: 'conf/conf.d/SSL-sample.conf'
[PHPD] Loaded config file: 'conf/conf.d/WebSocketServer.conf'
Congratulatious! PHPDaemon is working!
Ubuntu ← Installation
#First of all you should install related utilities.
sudo -i
apt-get install gcc make libcurl4-openssl-dev libevent-dev git libevent
#Installing PHP 5.5.
apt-get install php5-cli php5-dev php-pear
#Then install PHP modules.
pecl install event eio
echo "extension=event.so" > /etc/php5/mods-available/event.ini
echo "extension=eio.so" > /etc/php5/mods-available/eio.ini
#Creating links
ln -s /etc/php5/mods-available/event.ini /etc/php5/cli/conf.d/event.ini
ln -s /etc/php5/mods-available/eio.ini /etc/php5/cli/conf.d/eio.ini
#Prepare a folder for PHPDaemon.
mkdir /opt/phpdaemon
chown [your user]:[your group] /opt/phpdaemon
exit #exiting root user
#Installing PHPDaemon.
cd /opt/phpdaemon
git clone https://github.com/kakserpom/phpdaemon.git ./
#Creating configuration file from sample.
cp /opt/phpdaemon/conf/phpd.conf.example /opt/phpdaemon/conf/phpd.conf
#Let's create an alias of `phpd` for convenience.
alias phpd='/opt/phpdaemon/bin/phpd'
#Local alias of sudo:
alias sudo='sudo '
Then run the thing:
$ sudo phpd start --verbose-tty=1
Option --verbose-tty=1
turns on logging into STDOUT
If you see something like this:
[PHPD] Loaded config file: '/opt/phpdaemon/conf/phpd.conf'
[PHPD] Loaded config file: 'conf/conf.d/ExampleJabberBot.conf'
[PHPD] Loaded config file: 'conf/conf.d/FastCGI.conf'
[PHPD] Loaded config file: 'conf/conf.d/FlashpolicyServer.conf'
[PHPD] Loaded config file: 'conf/conf.d/HTTPServer.conf'
[PHPD] Loaded config file: 'conf/conf.d/IdentServer.conf'
[PHPD] Loaded config file: 'conf/conf.d/SSL-sample.conf'
[PHPD] Loaded config file: 'conf/conf.d/WebSocketServer.conf'
Congratulatious! PHPDaemon is working!
Let's make the aliases permanent:
echo "alias phpd='/opt/phpdaemon/bin/phpd'" >> ~/.bashrc
echo "alias sudo='sudo /opt/phpdaemon/bin/phpd'" >> ~/.bashrc
Gentoo ← Installation
You may install PHPDaemon with layman overlay.
Add this reference into the overlays section in layman.cfg file:
https://github.com/lexa-uw/layman-phpdaemon/blob/master/layman.xml
It should like that:
overlays : http://www.gentoo.org/proj/en/overlays/repositories.xml
https://github.com/lexa-uw/layman-phpdaemon/blob/master/layman.xml
Execute the following commands:
sudo layman -L
sudo layman -a phpdaemon
sudo emerge www-servers/phpdaemon
For example, below command install phpdaemon by version 0.4.1, 1.0_beta2 and weekly release.
$ sudo emerge "=www-servers/phpdaemon-0.4.1" "=www-servers/phpdaemon-1.0_beta2" "www-servers/phpdaemon"
These are the packages that would be merged, in order:
Calculating dependencies... done!
[ebuild R ~] www-servers/phpdaemon-0.4.1:0.4::phpdaemon USE="libevent -examples -runkit" 0 kB
[ebuild R ~] www-servers/phpdaemon-1.0_beta2:1.0::phpdaemon USE="eio event -runkit" 0 kB
[ebuild R ~] www-servers/phpdaemon-20130907:weekly::phpdaemon USE="eio event -runkit" 0 kB
...
After installation you can use "eselect phpdaemon set" tool for set up symlink for /usr/bin/phpd
$ sudo eselect phpdaemon list
Available phpdaemon targets:
[1] phpd0.4
[2] phpd1.0
[3] phpdweekly
$ sudo eselect phpdaemon set 3
$ sudo eselect phpdaemon show
Current phpdaemon:
weekly
Add phpdaemon to autoload:
$ rc-update add phpd default
* service phpd added to runlevel default
Add sepatare init.d scripts for different versions:
$ ln -s /etc/init.d/phpd /etc/init.d/phpd-0.4
$ ln -s /etc/init.d/phpd /etc/init.d/phpd-1.0
$ ln -s /etc/init.d/phpd /etc/init.d/phpd-weekly
And add phpd-1.0 to autoload:
$ rc-update add phpd-1.0 default
* service phpd added to runlevel default
Basics
PHPDaemon represents one master process with multiple workflows.
Application, depending on the load, is initialized to one or more workflows. In the second case, the request will be given one free workflow.
Mechanism of interaction between rebochimi processes is not provided, so for synchronization applications in different processes, you can use third-party software, such as Redis. It is also possible to specify the application option limit-instances N;
to limit the number of copies of the application in all operating processes.
The executable file is located in dirktor ./bin/phpd
.
You can create your own executable file, as shown in the example ./bin/sampleapp
.
Before starting the daemon checks for a variable $configFile
, using it to load the configuration.
Псевдотипы ← Basics
url ← Псевдотипы ← Basics
Pseudotype url @TODO
Control
$ phpd start |
Launch daemon |
$ phpd stop |
Stop daemonSYSCTL: SIGTERM, SIGQUIT |
$ phpd hardstop |
Force-stop daemonSYSCTL: SIGINT, SIGKILL |
$ phpd update |
Update configurationSYSCTL: SIGHUP |
$ phpd reload |
Graceful restart of all work processesSYSCTL: SIGUSR2 |
$ phpd reopenlog |
Reopen journalSYSCTL: SIGUSR1 |
$ phpd restart |
Graceful daemon restart |
$ phpd hardrestart |
Force-restart daemon |
$ phpd status |
Show daemon status |
$ phpd fullstatus |
Show detailed information about daemon |
$ phpd configtest |
Show global options. The value in parentheses is the default value. |
$ phpd log [-n K] |
Log output in real time using the command tail -f . With parameter -n K print last K lines. Or use -n +K to output starting with line K. |
$ phpd runworker |
Starting a workflow without a master process. Used for debugging. |
Examples
Examples
App resolver
When receiving requests, the daemon must first determine which application it should pass processing to.
This is done using the getRequestRoute
method in the AppResolver class.
You can define your own handler - an example can be found in ./conf/AppResolver.php
[https://github.com/kakserpom/phpdaemon/blob/master/conf/AppResolver.php].
The getRequestRoute
method has two arguments:
$req
—stdClass
object, containing the query parameters;$upstream
— a server object containing the incoming requests, for examplePHPDaemon\Servers\HTTP\Connection
.
The return value of this method can be:
- Name of the application;
null
to attempt to pass the request to the default application;false
to finish processing the request.
Don't forget to specify in config the path to your AppResolver, for example path './conf/AppResolver.php';
.
In the settings of the server receiving the requests, you can use the responder
option to specify the default name of the application to which the request will be passed if getRequestRoute
returns null
.
Configuration
Data types ← Configuration
Most phpdaemon options are described by their data types, allowing you to specify values in an extended format.
Size ← Data types ← Configuration
This is used to specify an amount of data. It can be written either as a whole number or as a whole number with a suffix.
Format: integer [bBkKmMgG]?
Suffix | Factor | Example | Value |
---|---|---|---|
b, B | 1 | 1b | 1 |
k | 1000 | 1k | 1000 |
K | 1024 | 1K | 1024 |
m | 1000 * 1000 | 1m | 1000000 |
M | 1024 * 1024 | 1M | 1048576 |
g | 1000 * 1000 * 1000 | 1g | 1000000000 |
G | 1024 * 1024 * 1024 | 1G | 1073741824 |
Time ← Data types ← Configuration
This is used to specify a number of seconds. The number can be floating point using the decimal separator "."
only.
Format: float [smhd]?
or (float [smhd])+
Suffix | Factor | Example | Value |
---|---|---|---|
s | 1 | 1s | 1 |
m | 60 | 1m | 60 |
h | 60 * 60 | 2h 12s | 7212 |
d | 60 * 60 * 24 | 1d 15m 32s | 87332 |
Number ← Data types ← Configuration
This is used to specify numbers.
Format: integer [kKmMgG]?
Suffix | Factor | Example | Value |
---|---|---|---|
k, K | 1000 | 1k | 1000 |
m, M | 1000 * 1000 | 1M | 1000000 |
g, G | 1000 * 1000 * 1000 | 1g | 1000000000 |
Global Options ← Configuration
There are two ways to set options:
- Configuration file
./conf/phpd.conf
; - Command line parameters, e.g.
--max-workers=1
.
The command line parameters have higher priority.
Configuration file ← Global Options ← Configuration
Options are specified in the following format:
option-name;
or option-name value;
option-name
is case insensitive, hyphens "-"
are ignored.
Thus, the following spellings are equivalent:
add-include-path
;addincludepath
;addIncludePath
;ADDInclude-path
.
The value may not exist at all, which equals to bool(true)
, or may be written in the following ways:
null
;- a boolean expression
false
ortrue
; - a whole number;
- a floating point number;
- a string; if the string contains a space character
" "
or a comma","
then the string must be wrapped in single or double quotes.; - an array.
To write an array, the space " "
or comma ","
separator is used. You can use both separators within the same value.
Example option | var_dump output |
---|---|
var-name; | bool(true) |
var-name null; | NULL |
var-name true; | bool(true) |
var-name false; | bool(false) |
var-name 0; | int(0) |
var-name 1; | int(1) |
var-name 3.14; | float(3.14) |
var-name "3.14"; | string(4) "3.14" |
var-name "example. long line, second example"; | string(34) "example. long line, second example" |
var-name example. long line, second example; | array(5) { [0]=> string(8) "example." [1]=> string(4) "long" [2]=> string(4) "line" [3]=> string(6) "second" [4]=> string(7) "example" } |
var-name 1, 'a' null 3.14 'a word or two'; | array(5) { [0]=> int(1) [1]=> string(1) "a" [2]=> NULL [3]=> float(3.14) [4]=> string(13) "a word or two" } |
The available global options for the daemon are listed below in the following format:
option-name (data-type = default-value);
Graceful restart of worker processes ← Global Options ← Configuration
-
max-requests (Number = '10k')
Maximum number of requests before restarting the worker.0
– unlimited -
max-memory-usage (Size = '0b')
Maximum allowed memory consumption threshold for the worker.0
– unlimited -
max-idle (Time = '0s')
Maximum process time running in idle before restarting.0
– unlimited -
auto-reload (Time = '0s')
Sets the check interval for all loaded files. Gracefully reboots worker if any files are changed. auto-reimport (boolean = false)
Imports methods and functions on-the-fly from modified files using runkit, without rebooting the worker.
Main paths ← Global Options ← Configuration
-
pid-file (string = '/var/run/phpd.pid')
The path to the pid file. Make sure you have write access. -
config-file (string = '/etc/phpdaemon/phpd.conf;/etc/phpd/phpd.conf;./conf/phpd.conf')
The path to the configuration file. You can specify several through the separator";
. Only the first found configuration file will be loaded. -
path (string = '/etc/phpdaemon/AppResolver.php;./conf/AppResolver.php')
Path to the Application Resolver. You can specify several via the separator";
. Only the first found file will be loaded. add-include-path (string = null)
Additional paths for the php.ini option include_path. You can specify multiple paths by using the colon":"
separator.
Related to the master process ← Global Options ← Configuration
-
mpm-delay (Time = '0.1s')
Multi-Process Manager interval. The MPM is responsible for starting/shutting down worker processes according to the settings. -
start-workers (Number = 4)
The number of initial workers when you start the daemon. -
min-workers (Number = 4)
Minimum number of worker processes allowed. -
max-workers (Number = 8)
Maximum number of worker processes allowed. -
min-spare-workers (Number = 2)
Minimum number of idle workers: phpDaemon will run additional workers when the load increases so that there are enough idle workers but no more in total than specified in the max-workers parameter. -
max-spare-workers (Number = 0)
Maximum number of idle worker processes. phpDaemon will shut down additional worker processes when the load drops. -
master-priorty (Number = 100)
The priority of the master process. The lower the value, the higher the priority. -
ipc-thread-priority (Number = 100)
IPC process priority. The lower the value, the higher the priority. -
worker-priority (Number = 4)
Worker priority. The lower the value, the higher the priority. throw-exception-on-shutdown (boolean = false)
Throw exceptionException('event shutdown')
after the process has finished.
Requests ← Global Options ← Configuration
-
locale (string = '')
Sets the locale. You can specify several via a separator","
. ob-filter-auto (boolean = true)
Enable standardob_
filter.
Worker processes ← Global Options ← Configuration
-
chroot (string = '/')
Changing the system root for worker processes. -
cwd (string = '.')
Setting up the current work directory for worker processes. -
user (string = null)
The user for worker processes. Use a secure user, do not use root if you don't know what you're doing. -
group (string = null)
A group for worker processes. Use a secure group, do not use root if you don't know what you're doing. auto-gc (Number = '1k')
Enables a garbage collector called every n requests.0
– turns off the garbage collector completely.
Logging and debugging ← Global Options ← Configuration
-
logging (boolean = true)
Enables logging. -
log-storage (string = '/var/log/phpdaemon.log')
The path to the log file. -
log-errors (boolean = true)
Enables logging of local errors such as Undefined route in WebSocketServer, etc. -
log-worker-set-state (boolean = false)
Enables logging of worker status changes. -
log-events (boolean = false)
Enables logging of events. -
log-signals (boolean = false)
Enables logging of system signals. -
verbose-tty (boolean = false)
If this parameter is enabled, the log is printed to the terminal (STDOUT).Please note that in the normal launch variant (not runworker) the input from the terminal is ignored, although after launch with this parameter it may seem that the program is bound to the terminal.
restrict-error-control (boolean = false)
Switches off the error control operator "@".
POSIX I/O subsystem ← Global Options ← Configuration
-
eio-enabled (boolean = true)
Enables EIO support. -
eio-set-max-idle (Time = null)
Sets the maximum number of waiting threads. -
eio-set-min-parallel (Number = null)
Sets the minimum number of parallel threads. -
eio-set-max-parallel (Number = null)
Sets the maximum number of parallel threads. -
eio-set-max-poll-reqs (Number = null)
Sets the maximum number of requests processed. eio-set-max-poll-time (Time = null)
Sets the maximum run time.
Applications ← Configuration
-
enable
(boolean = true) It allows the application to initialize the daemon. By DEFAULT DATA-described application, always included in the configuration file. limit-instances
(integer = null) It limits the number of initialized applications in all operating processes. The default is no limit.
Development
Application ← Development
Appendix B is a subclass phpDaemon AppInstance, to create a new application, you must create a file applications / [name] .php and call it class Example extends AppInstance. Then, the kernel will call methods in response to which the application must perform the required operations:
init() - initialize the application. The application needs to maintain the required dependencies and prepare for the launch. onReady() - it means that the working process in which the application is ready to run processing. onShutdown() - the completion of the application. beginRequest(Request $ req, AppInstance $ upstream) - sought a new request object to the application. The method can return false, this means that the application is refused (or not able) to handle requests. After calling this method, the request object enters the queue and invoked iteratively. The class is declared as class ExampleRequest extends Request. Methods:
init() - is invoked only once when creating the request object. run() - called the dispatcher queue to ter long as it will be returned code 1 or terminate method is called (). terminate() - it should not be rebooted. Method interrupts and terminates the request. sleep($seconds) - the time in seconds after which you want to return to the query. wakeup() - interrupt sleep. onAbort() - request a reset event is called if the client fell off. header($header) - set the HTTP-response header. out($str) - to write to the output stream line. combinedOut($str) - write a string to the output stream containing both headers and body. stdin($str) - processor input stream of the request. finish($status) - 0 - normal, -1 - abort, -2 - termination chunked() - set Transfer-Encoding: chunked.
Processing Query ← Development
Servers and clients ← Development
Debug ← Development
Servers
Servers are responsible for receiving requests and passing them to applications.
Each server is a class inherited from Network\Server, which in turn is inherited from Network\Pool. The server can be initiated directly in the user application, for example:
/* ... */
$this->pool = \PHPDaemon\Servers\FlashPolicy::getInstance([
'listen' => 'tcp://0.0.0.0:843'
]);
$this->pool->onReady();
/* ... */
But do not forget that in this case you should send onReady(), onShutdown() and onConfigUpdated() events.
In most cases, the server is run by the Pool application of the same name.
# context for ssl connection (optional)
TransportContext:myContext {
tls;
certFile "/path/to/cert.pem";
pkFile "/path/to/privkey.pem";
passphrase "";
verifyPeer true;
allowSelfSigned true;
}
# listening to port 80 and 443
Pool:HTTPServer {
listen "tcp://0.0.0.0:80", "tcp://0.0.0.0:443##myContext";
port 80;
privileged;
maxconcurrency 1;
}
Server options ← Servers
This section lists the options used by all servers.
-
listen (string|array)
The addresses that the server is listening to. You can specify several via a separator","
. -
privileged
@TODO -
max-concurrency
Maximum number of open connections. -
max-allowed-packet
Maximum allowed package size. -
connection-class
Default connection class. -
name
@TODO -
allowed-clients
Allowed IP addresses or comma-separated masks. -
ssl
Enables SSL. -
ssl-port
@TODO -
cert-file
@TODO -
pk-file
@TODO -
passphrase
@TODO -
verify-peer
@TODO -
allow-self-signed
@TODO -
verify-depth
@TODO ca-file
@TODO
HTTP ← Servers
The server uses the namespace HTTPRequest.
This vehicle application provides HTTP server for phpDaemon. Incoming connections will be transferred Websocket WebsocketServer application.
HTTP is trying to determine the application through AppResolver, be sure to configure it.
namespace PHPDaemon\Servers\HTTP;
class Connection extends \PHPDaemon\Network\Connection;
Constants ← Connection ← HTTP ← Servers
-
const STATE_FIRSTLINE = 1
- @TODO DESCR
-
const STATE_HEADERS = 2
- @TODO DESCR
-
const STATE_CONTENT = 3
- @TODO DESCR
-
const STATE_PROCESSING = 4
- @TODO DESCR
Methods ← Connection ← HTTP ← Servers
-
boolean public function checkSendfileCap ( )
- Check if Sendfile is supported here
-
boolean public function checkChunkedEncCap ( )
- Check if Chunked encoding is supported here
-
integer public function getKeepaliveTimeout ( )
-
boolean public function requestOut ( object $req, string $s )
- Handles the output from downstream requests
$req
— \PHPDaemon\Request\Generic$s
— The output
-
void public function endRequest ( )
- End request
-
void public function freeRequest ( )
- Frees this request
-
void public function onFinish ( )
- Called when connection is finished
-
void public function badRequest ( )
- Send Bad request
namespace PHPDaemon\Servers\HTTP;
class Pool extends \PHPDaemon\Network\Server;
-
listen (string|array = 'tcp://0.0.0.0')
Listen addresses -
port (integer = 80)
Listen port -
send-file (boolean = 0)
Enable X-Sendfile? -
send-file-dir (string = '/dev/shm')
Directory for X-Sendfile -
send-file-prefix (string = 'http-')
Prefix for files used for X-Sendfile -
send-file-onlybycommand (boolean = 0)
Use X-Sendfile only if server['USE_SENDFILE'] provided. -
expose (boolean = 1)
Expose PHPDaemon version by X-Powered-By Header -
keepalive (Time = '0s')
Keepalive time -
chunksize (Size = '8k')
Chunk size -
defaultcharset (string = 'utf-8')
Default charset -
wss-name (string = '')
Related WebSocketServer instance name -
fps-name (string = '')
Related FlashPolicyServer instance name -
upload-max-size (Size = ini_get('upload_max_filesize'))
Maximum uploading file size. responder (string = null)
Reponder application (if you do not want to use AppResolver)
-
string public $variablesOrder
- Variables order "GPC"
-
\WebSocketServer public $WS
- WebSocketServer instance
-
void public function onConfigUpdated ( )
- Called when worker is going to update configuration
-
void public function onReady ( )
- Called when the worker is ready to go
FastCGI ← Servers
The server uses the namespace HTTPRequest.
This vehicle is an application server for FastCGI phpDaemon.
After configuring phpDaemon you should also use a Web server that supports FastCGI. If you have not made a choice in favor of one of them, we recommend to NGINX.
The web server can transmit the FastCGI-server option APPNAME, which contains the name of the application that should handle the request. If not passed, FastCGI-server will try to determine this through AppResolver.
Configuration example NGINX:
location /Example/ {
fastcgi_pass unix:/tmp/phpdaemon.fcgi.sock;
fastcgi_param APPNAME Example;
include fastcgi_params;
}
namespace PHPDaemon\Servers\FastCGI;
class Connection extends \PHPDaemon\Network\Connection;
Constants ← Connection ← FastCGI ← Servers
-
const FCGI_BEGIN_REQUEST = 1
-
const FCGI_ABORT_REQUEST = 2
-
const FCGI_END_REQUEST = 3
-
const FCGI_PARAMS = 4
-
const FCGI_STDIN = 5
-
const FCGI_STDOUT = 6
-
const FCGI_STDERR = 7
-
const FCGI_DATA = 8
-
const FCGI_GET_VALUES = 9
-
const FCGI_GET_VALUES_RESULT = 10
-
const FCGI_UNKNOWN_TYPE = 11
-
const FCGI_RESPONDER = 1
-
const FCGI_AUTHORIZER = 2
-
const FCGI_FILTER = 3
-
const STATE_CONTENT = 1
-
const STATE_PADDING = 2
Properties ← Connection ← FastCGI ← Servers
-
public $timeout = 180
Methods ← Connection ← FastCGI ← Servers
-
boolean public function checkSendfileCap ( )
- Is this upstream suitable for sendfile()?
-
boolean public function checkChunkedEncCap ( )
- Is this upstream suitable for chunked encoding?
-
integer public function getKeepaliveTimeout ( )
-
void public function onRead ( )
- Called when new data received
-
boolean public function requestOut ( object $req, string $out )
- Handles the output from downstream requests
$req
— Request$out
— The output
-
boolean public function sendChunk ( object $req, string $chunk )
- Sends a chunk
$req
— Request$chunk
— Data
-
void public function freeRequest ( object $req )
- Frees request
$req
-
void public function endRequest ( object $req, string $appStatus, string $protoStatus )
- Handles the output from downstream requests
$req
$appStatus
$protoStatus
-
void public function badRequest ( object $req )
- Send Bad request
$req
namespace PHPDaemon\Servers\FastCGI;
class Pool extends \PHPDaemon\Network\Server;
-
listen (string|array = 'tcp://127.0.0.1,unix:///tmp/phpdaemon.fcgi.sock')
Listen addresses -
port (integer = 9000)
Listen port -
auto-read-body-file (boolean = 1)
Read request body from the file given in REQUEST_BODY_FILE parameter -
allowed-clients (string = '127.0.0.1')
Allowed clients ip list -
send-file (boolean = 0)
Enable X-Sendfile? -
send-file-dir (string = '/dev/shm')
Directory for X-Sendfile -
send-file-prefix (string = 'fcgi-')
Prefix for files used for X-Sendfile -
send-file-onlybycommand (boolean = 0)
Use X-Sendfile only if server['USE_SENDFILE'] provided. -
expose (boolean = 1)
Expose PHPDaemon version by X-Powered-By Header -
keepalive (Time = '0s')
Keepalive time -
chunksize (Size = '8k')
Chunk size -
defaultcharset (string = 'utf-8')
Default charset upload-max-size (Size = ini_get('upload_max_filesize'))
Maximum uploading file size.
-
string public $variablesOrder
- "GPC" Variables order
-
void public function onConfigUpdated ( )
- Called when worker is going to update configuration
DebugConsole ← Servers
This vehicle application provides interactive debugging console phpDaemon.
# telnet 127.0.0.1 8818
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Welcome! DebugConsole for phpDaemon.
login secret
OK.
eval echo 123;
123
Connection ← DebugConsole ← Servers
namespace PHPDaemon\Servers\DebugConsole;
class Connection extends \PHPDaemon\Network\Connection;
Properties ← Connection ← DebugConsole ← Servers
-
integer public $timeout = 60
- Timeout
Methods ← Connection ← DebugConsole ← Servers
-
void public function onReady ( )
- onReady
-
void public function onRead ( )
- Called when new data received
Pool ← DebugConsole ← Servers
namespace PHPDaemon\Servers\DebugConsole;
class Pool extends \PHPDaemon\Network\Server;
Options ← Pool ← DebugConsole ← Servers
-
listen (string|array = 'tcp://127.0.0.1')
Listen addresses -
port (integer = 8818)
Listen port passphrase (string = 'secret')
Password for auth
FlashPolicy ← Servers
This simple application provides Flashpolicy server phpDaemon.
This application should be included in case you want to connect to a server via Flash.
Connection ← FlashPolicy ← Servers
namespace PHPDaemon\Servers\FlashPolicy;
class Connection extends \PHPDaemon\Network\Connection;
Methods ← Connection ← FlashPolicy ← Servers
-
void public function onRead ( )
- Called when new data received
Pool ← FlashPolicy ← Servers
namespace PHPDaemon\Servers\FlashPolicy;
class Pool extends \PHPDaemon\Network\Server;
Options ← Pool ← FlashPolicy ← Servers
-
listen (string|array = '0.0.0.0')
Listen addresses -
port (integer = 843)
Listen port file (string = getcwd() . '/conf/crossdomain.xml')
Path to crossdomain.xml file
Properties ← Pool ← FlashPolicy ← Servers
-
string public $policyData
- Cached policy file contents
Methods ← Pool ← FlashPolicy ← Servers
-
void public function onReady ( )
- Called when worker is ready
-
void public function onConfigUpdated ( )
- Called when worker is going to update configuration
Ident ← Servers
namespace PHPDaemon\Servers\Ident;
class Connection extends \PHPDaemon\Network\Connection;
namespace PHPDaemon\Servers\Ident;
class Pool extends \PHPDaemon\Network\Server;
-
listen (string|array = '0.0.0.0')
Listen addresses port (integer = 113)
Listen port
-
void public function RPCall ( string $method, array $args )
- Function handles incoming Remote Procedure Calls
You can override it $method
— Method name$args
— Arguments
- Function handles incoming Remote Procedure Calls
-
void public function registerPair ( integer $local, integer $foreign, string $user )
- Register pair
$local
— Local$foreign
— Foreign$user
— User
-
void public function unregisterPair ( integer $local, integer $foreign )
- Unregister pair
$local
— Local$foreign
— Foreign
-
string public function findPair ( integer $local, integer $foreign )
- Find pair
$local
— Local$foreign
— Foreign
IRCBouncer ← Servers
Connection ← IRCBouncer ← Servers
namespace PHPDaemon\Servers\IRCBouncer;
class Connection extends \PHPDaemon\Network\Connection;
Properties ← Connection ← IRCBouncer ← Servers
-
string public $EOL = '\r\n'
-
object public $attachedServer
-
string public $usermask
-
integer public $latency
-
integer public $lastPingTS
-
integer public $timeout = 180
-
boolean public $protologging = false
Methods ← Connection ← IRCBouncer ← Servers
-
void public function onReady ( )
- Called when the connection is handshaked (at low-level), and peer is ready to recv. data
-
void public function onFinish ( )
-
void public function ping ( )
-
void public function command ( string $from, string $cmd, mixed $args )
$from
— From$cmd
— Command$args
— Arguments
-
void public function commandArr ( string $from, string $cmd, array $args )
$from
— From$cmd
— Command$args
— Arguments
-
void public function detach ( )
-
void public function attachTo ( )
-
void public function exportChannel ( object $chan )
$chan
-
void public function onCommand ( string $cmd, array $args )
$cmd
— Command$args
— Arguments
-
void public function msgFromBNC ( string $msg )
$msg
-
void public function onRead ( )
- Called when new data received
Pool ← IRCBouncer ← Servers
namespace PHPDaemon\Servers\IRCBouncer;
class Pool extends \PHPDaemon\Network\Server;
Options ← Pool ← IRCBouncer ← Servers
-
listen (string|array = '0.0.0.0')
Listen addresses -
port (integer = 6667)
Listen port -
url (string = 'irc://user@host/nickname/realname')
URL -
servername (string = 'bnchost.tld')
Server name -
defaultchannels (string = '')
Default channels -
protologging (boolean = 0)
Logging? -
dbname (string = 'bnc')
Database name password (string = 'SecretPwd')
Password
Properties ← Pool ← IRCBouncer ← Servers
-
\Pool public $client
-
\Connection public $conn
-
boolean public $protologging = false
-
\Pool public $db
-
object public $messages
-
object public $channels
Methods ← Pool ← IRCBouncer ← Servers
-
void public function applyConfig ( )
-
void public function onReady ( )
-
void public function getConnection ( string $url )
$url
Lock ← Servers
It requires refactoring
namespace PHPDaemon\Servers\Lock;
class Connection extends \PHPDaemon\Network\Connection;
Properties ← Connection ← Lock ← Servers
-
boolean public $server = false
- Is this S2S-session?
-
array public $locks = [ ]
- State of locks
Methods ← Connection ← Lock ← Servers
-
string public function acquireLock ( string $name, boolean $wait = FALSE )
- Called when client is trying to acquire lock
$name
— Name of job$wait
— Wait if already acquired?
-
void public function done ( string $name, string $result )
- Called when client sends done- or failed-event
$name
— Name of job$result
— Result
-
void public function onFinish ( )
- Event of Connection
-
void public function stdin ( string $buf )
- Called when new data received
$buf
— New data
namespace PHPDaemon\Servers\Lock;
class Pool extends \PHPDaemon\Network\Server;
-
listen (string|array = 'tcp://0.0.0.0')
Listen addresses -
listenport (integer = 833)
Listen port -
allowedclients (string = '127.0.0.1')
Allowed clients ip list -
enable (boolean = 0)
Disabled by default protologging (boolean = false)
Logging?
-
array public $lockState = [ ]
- Jobs
-
array public $lockConnState = [ ]
- Array of connection's state
Socks ← Servers
namespace PHPDaemon\Servers\Socks;
class Connection extends \PHPDaemon\Network\Connection;
Constants ← Connection ← Socks ← Servers
-
const STATE_ABORTED = 1
- @TODO DESCR
-
const STATE_HANDSHAKED = 2
- @TODO DESCR
-
const STATE_AUTHORIZED = 3
- @TODO DESCR
-
const STATE_DATAFLOW = 4
- @TODO DESCR
Methods ← Connection ← Socks ← Servers
-
void public function onRead ( )
- Called when new data received
-
void public function onSlaveReady ( integer $code, string $addr, integer $port )
$code
$addr
$port
-
void public function onFinish ( )
namespace PHPDaemon\Servers\Socks;
class SlaveConnection extends \PHPDaemon\Servers\Socks\Connection;
Methods ← SlaveConnection ← Socks ← Servers
-
void public function setClient ( \SocksServerConnection $client )
- Set client
$client
-
void public function onRead ( )
- Called when new data received
-
void public function onFinish ( )
- Event of Connection
namespace PHPDaemon\Servers\Socks;
class Pool extends \PHPDaemon\Network\Server;
-
listen (string|array = 'tcp://0.0.0.0')
Listen addresses -
port (integer = 1080)
Listen port -
auth (boolean = 0)
Authentication required -
username (string = 'User')
User name -
password (string = 'Password')
Password allowedclients (string = null)
Allowed clients ip list
WebSocket ← Servers
The server uses the namespace HTTPRequest.
This vehicle is an application WebSocket server phpDaemon.
Your application must obtain a reference to an instance and call WebSocketServer addRoute() to add their own ways. Callback-way function must return a new instance of your class that inherits from WebSocketRoute determines onFrame method. Inside the method onFrame we can contact $this->client->sendFrame() to send packets to the client.
namespace PHPDaemon\Servers\WebSocket;
class Connection extends \PHPDaemon\Network\Connection;
Constants ← Connection ← WebSocket ← Servers
-
const STATE_FIRSTLINE = 1
- State: first line
-
const STATE_HEADERS = 2
- State: headers
-
const STATE_CONTENT = 3
- State: content
-
const STATE_PREHANDSHAKE = 5
- State: prehandshake
-
const STATE_HANDSHAKED = 6
- State: handshaked
Properties ← Connection ← WebSocket ← Servers
-
public $session
-
string public $framebuf = ''
- Frame buffer
-
array public $server = [ ]
- _SERVER
-
array public $cookie = [ ]
- _COOKIE
-
array public $get = [ ]
- _GET
-
null public $post
- _POST
-
array public static $hvaltr = [ '; ' => '&', ';' => '&', ' ' => '%20', ]
- Replacement pairs for processing some header values in parse_str()
Methods ← Connection ← WebSocket ← Servers
-
void public function onReady ( )
- Called when the stream is handshaked (at low-level), and peer is ready to recv. data
-
void public function onWakeup ( )
- Called when the request wakes up
-
void public function onSleep ( )
- Called when the request starts sleep
-
void public function onInheritanceFromRequest ( object $req )
- Called when connection is inherited from HTTP request
$req
-
boolean public function sendFrame ( string $data, string $type = null, callable $cb = null )
- Sends a frame
$data
— Frame's data$type
— Frame's type. ("STRING" OR "BINARY")$cb
—callback ( )
— Optional. Callback called when the frame is received by client
-
void public function onFinish ( )
- Event of Connection
-
boolean public function handleException ( \Exception $e )
- Uncaught exception handler
$e
-
boolean public function onFrame ( string $data, string $type )
- Called when new frame received
$data
— Frame's data$type
— Frame's type ("STRING" OR "BINARY")
-
boolean public function onHandshake ( )
- Called when the connection is handshaked
-
boolean public function gracefulShutdown ( )
- Called when the worker is going to shutdown
-
boolean public function handshake ( array $extraHeaders = null )
- Called when we're going to handshake
$extraHeaders
-
void public function write ( string $s )
$s
— Data
-
void public function badRequest ( )
- Send Bad request
-
boolean public function status ( integer $code = 200 )
- Send HTTP-status
$code
— Code
-
boolean public function header ( string $s, boolean $replace = true, boolean $code = false )
- Send the header
$s
— Header. Example: 'Location: http://php.net/'$replace
— Optional. Replace?$code
— Optional. HTTP response code
namespace PHPDaemon\Servers\WebSocket;
class Pool extends \PHPDaemon\Network\Server;
-
expose (boolean = 1)
Expose PHPDaemon version by X-Powered-By Header -
listen (string|array = '0.0.0.0')
Listen addresses -
port (integer = 8047)
Listen port -
max-allowed-packet (Size = '1M')
Maximum allowed size of packet fps-name (string = '')
Related FlashPolicyServer instance name
-
const BINARY = 'BINARY'
- Binary packet type
-
const STRING = 'STRING'
- String packet type
-
array public $routes = [ ]
-
boolean public function setRouteOptions ( string $path, array $opts )
- Sets an array of options associated to the route
$path
— Route name$opts
— Options
-
array public function getRouteOptions ( string $path )
- Return options by route
$path
— Route name
-
boolean public function addRoute ( string $path, callable $cb )
- Adds a route if it doesn't exist already
$path
— Route name$cb
—callback ( )
— Route's callback
-
mixed public function getRoute ( string $path, object $client, boolean $withoutCustomTransport = false )
$path
$client
$withoutCustomTransport
-
boolean public function setRoute ( string $path, callable $cb )
- Force add/replace a route
$path
— Path$cb
—callback ( )
— Callback
-
boolean public function removeRoute ( string $path )
- Removes a route
$path
— Route name
-
boolean public function routeExists ( string $path )
- Checks if route exists
$path
— Route name
Clients
At the heart of all customers is the namespace the Network, the study of which will give a greater understanding of customer opportunities and networking daemon as a whole.
Basics ← Clients
-
server (string)
erver address. Records a special format described in the section Option server -
servers (array)
Addresses of servers recorded in the option format server, separated by a comma ,. When a client connects to use randomly selected server. Note, this option will be ignored if the option is set server. maxconnperserv
protologging
Asterisk ← Clients
namespace PHPDaemon\Clients\Asterisk;
Раздел устарел!
Asterisk - is an open-source PBX. AMI - Asterisk's software interface (API) for system management, which allows developers to send commands to the server, read the results of their execution, as well as receive notifications about events in real time. The Asterisk client provides a high-level interface to AMI, allowing developers to control the Asterisk server from applications.
The documentation of the client is based on the material in the book Asterisk: будущее телефонии.
@TODO it's from the wiki, check it out.
Before sending commands and receiving events from the server, you need to get the connection session(s) in your application. In your application you receive the AsteriskDriver object through:
$this->pbxDriver = Daemon::$appResolver->getInstanceByAppName('AsteriskDriver');
Next you get the AsteriskDriverSession object through:
$session = $this->pbxDriver->getConnection();
// или
foreach($this->pbxConnections as $addr => $conn) {
$session = $this->pbxDriver->getConnection($addr);
// do something...
}
Add (composition) to it the current connection context by means of:
$session->context = $this;
On connect:
$session->onConnected(function(SocketSession $session, $status) {
// your code, depending on the connection
});
On disconnect:
$session->onFinish(function(SocketSession $session) {
// maybe run reconnect interval
});
Suppose that you have multiple Asterisk servers from which you want to receive events and to which you want to send action commands. You also want to track down connection failure and perform a reconnect. See below for an example on how to reconnect.
Although AMI is a string-based protocol, the driver works with associative arrays during I/O. When an action or event is replied to, all headers and their values are case-sensitive if the value does not contain case-sensitive information, such as the name of the pirate.
To send a command and receive a response, you can use either the helper method, which has a detailed explanation in the Asterisk documentation, or the universal Connection::action method.
In any case, for each command you define a callback function to which the connection session object and an associative header-value pair array will be passed.
The client correctly handles that the order of response packets is not defined and correctly assembles the response packets.
$session->getSipPeers(function(SocketSession $session, array $packet) {
// $session->addr contain the connection address
// $session->context contains the call context (if installed)
// $packet - is an array of response header-value pairs.
// do something
})
// or
$session->getConfig('chan_dahdi.conf', array($this, 'doSomething'));
public function doSomething(SocketSession $session, array $packet) {
}
// or
$session->action('Ping', function(SocketSession $session, array $packet) {
if($packet['response'] == 'success' && $packet['ping'] == 'pong') {
// successfully played ping-pong
}
});
// or
// $channel contains the channel from the event
$session->redirect(array(
'Channel' => $channel,
'Context' => 'internal',
'Exten' => '116',
'Priority' => 1
), function(SocketSession $session, array $packet) {
// find out whether it was successful or not from the server response contained in the $packet associative array
});
The callback function when an event occurs in this connection is defined once and passed to the onEvent() method.
$session->onEvent(array($this, 'onPbxEvent'));
When several worker are launched, you can use the lock table to avoid that the channel events (which are characterized by a unique identifier (uniqueid) of the channel) are multiple of the number of workers. Here is an example, when MongoDB collection is used as a lock table, which allows to put a unique index on a document:
$session->onEvent(array($this, 'onPbxEvent'));
// db.events.ensureIndex({"event": 1, "addr": 1}, {unique: true});
public function onPbxEvent(SocketSession $session, array $event) {
if(method_exists('Foo_PbxEventDispatcher', "{$event['event']}Handler")) {
$handler = "{$event['event']}Handler";
if(isset($event['uniqueid']) || isset($event['uniqueid1'])) {
$appInstance = $this;
$this->db->events->insert(
array(
'ts' => microtime(true),
'event' => $event,
'addr' => $session->addr
),
function($result) use ($appInstance, $session, $event) {
if($result['err'] === null) {
$handler = "{$event['event']}Handler";
Foo_PbxEventDispatcher::$handler($appInstance, $session, $event);
}
}
);
}
else {
Foo_PbxEventDispatcher::$handler($this, $session, $event);
}
}
}
class Foo extends AppInstance {
// ...
public function onInit() {
// pbxConnections - array of connections
foreach($this->pbxConnections as $addr => $conn) {
$pbx_driver_session = $this->pbxDriver->getConnection($addr);
if($pbx_driver_session instanceof SocketSession) {
$pbx_driver_session->context = $this;
//$pbx_driver_session->onError(array($this, 'onPbxError'));
$pbx_driver_session->onConnected(array($this, 'onPbxConnected'));
$pbx_driver_session->onEvent(array($this, 'onPbxEvent'));
$pbx_driver_session->onFinish(array($this, 'onPbxFinish'));
}
else {
$this->runPbxReconnectInterval($pbx_driver_session);
}
}
}
// ...
public function onPbxConnected(SocketSession $session, $status) {
if($status) {
if($session->context instanceof PbxReconnector) {
$session->context->finish();
}
// do something...
}
else {
$this->runPbxReconnectInterval($session);
}
}
// ...
public function onPbxFinish(SocketSession $session) {
$this->runPbxReconnectInterval($session);
}
// ...
public function runPbxReconnectInterval(SocketSession $session) {
if(Daemon::$process->terminated) {
return;
}
foreach ($this->queue as &$r) {
if($r instanceof PbxReconnector) {
if ($r->attrs->addr == $session->addr) {
return;
}
}
}
$interval = $this->pushRequest(new PbxReconnector($this, $this));
$interval->attrs->addr = $session->addr;
}
// ...
}
// ...
class PbxReconnector extends Request {
public $interval = 0.3;
public function run() {
$pbx_driver_session = $this->appInstance->pbxDriver->getConnection($this->attrs->addr);
if($pbx_driver_session) {
if($this->appInstance->config->{'pbxreconnectorlogging'}->value) {
Daemon::log('Reconnecting to ' . $this->attrs->addr);
}
$pbx_driver_session->context = $this;
$pbx_driver_session->onConnected(array($this->appInstance, 'onPbxConnected'));
$pbx_driver_session->onFinish(array($this->appInstance, 'onPbxFinish'));
}
$this->sleep($this->interval);
}
}
namespace PHPDaemon\Clients\Asterisk;
class Connection extends \PHPDaemon\Network\ClientConnection;
Asterisk Call Manager Connection
Constants ← Connection ← Asterisk ← Clients
-
const CONN_STATE_START = 0
- @TODO DESCR
-
const CONN_STATE_GOT_INITIAL_PACKET = 0.1
- @TODO DESCR
-
const CONN_STATE_AUTH = 1
- @TODO DESCR
-
const CONN_STATE_LOGIN_PACKET_SENT = 1.1
- @TODO DESCR
-
const CONN_STATE_CHALLENGE_PACKET_SENT = 1.2
- @TODO DESCR
-
const CONN_STATE_LOGIN_PACKET_SENT_AFTER_CHALLENGE = 1.3
- @TODO DESCR
-
const CONN_STATE_HANDSHAKED_OK = 2.1
- @TODO DESCR
-
const CONN_STATE_HANDSHAKED_ERROR = 2.2
- @TODO DESCR
-
const INPUT_STATE_START = 0
- @TODO DESCR
-
const INPUT_STATE_END_OF_PACKET = 1
- @TODO DESCR
-
const INPUT_STATE_PROCESSING = 2
- @TODO DESCR
Properties ← Connection ← Asterisk ← Clients
-
string public $EOL = '\r\n'
- EOL
-
string public $username
- The username to access the interface
-
string public $secret
- The password defined in manager interface of server
-
float public $state = 0
- Connection's state
-
integer public $instate = 0
- Input state
-
array public $packets = [ ]
- Received packets
-
integer public $cnt = 0
- For composite response on action
-
array public $callbacks = [ ]
- Stack of callbacks called when response received
-
array public $assertions = [ ]
- Assertions for callbacks.
Assertion: if more events may follow as response this is a main part or full
an action complete event indicating that all data has been sent
- Assertions for callbacks.
-
callable public $onChallenge
- Callback. Called when received response on challenge action
Methods ← Connection ← Asterisk ← Clients
-
void public function onConnected ( callable )
- Execute the given callback when/if the connection is handshaked
Callback
-
void public function onReady ( )
- Called when the connection is handshaked (at low-level), and peer is ready to recv. data
-
boolean public function gracefulShutdown ( )
- Called when the worker is going to shutdown
-
void public function onFinish ( )
- Called when session finishes
-
void public function onRead ( )
- Called when new data received
-
void public function getSipPeers ( callable $cb )
- Action: SIPpeers
Synopsis: List SIP peers (text format)
Privilege: system,reporting,all
Description: Lists SIP peers in text format with details on current status.
Peerlist will follow as separate events, followed by a final event called
PeerlistComplete.
Variables:
ActionID:Action ID for this transaction. Will be returned $cb
—callback ( Connection $conn, array $packet )
— Callback called when response received
- Action: SIPpeers
-
void public function getIaxPeers ( callable $cb )
- Action: IAXpeerlist
Synopsis: List IAX Peers
Privilege: system,reporting,all $cb
—callback ( Connection $conn, array $packet )
— Callback called when response received
- Action: IAXpeerlist
-
void public function getConfig ( string $filename, callable $cb )
- Action: GetConfig
Synopsis: Retrieve configuration
Privilege: system,config,all
Description: A 'GetConfig' action will dump the contents of a configuration
file by category and contents or optionally by specified category only.
Variables: (Names marked with are required)
Filename: Configuration filename (e.g. foo.conf)
Category: Category in configuration file $filename
— Filename$cb
—callback ( Connection $conn, array $packet )
— Callback called when response received
- Action: GetConfig
-
void public function getConfigJSON ( string $filename, callable $cb )
- Action: GetConfigJSON
Synopsis: Retrieve configuration
Privilege: system,config,all
Description: A 'GetConfigJSON' action will dump the contents of a configuration
file by category and contents in JSON format. This only makes sense to be used
using rawman over the HTTP interface.
Variables:
Filename: Configuration filename (e.g. foo.conf) $filename
— Filename$cb
—callback ( Connection $conn, array $packet )
— Callback called when response received
- Action: GetConfigJSON
-
void public function setVar ( string $channel, string $variable, string $value, callable $cb )
- Action: Setvar
Synopsis: Set Channel Variable
Privilege: call,all
Description: Set a global or local channel variable.
Variables: (Names marked with are required)
Channel: Channel to set variable for
Variable: Variable name
*Value: Value $channel
$variable
$value
$cb
—callback ( Connection $conn, array $packet )
- Action: Setvar
-
void public function coreShowChannels ( callable $cb )
- Action: CoreShowChannels
Synopsis: List currently active channels
Privilege: system,reporting,all
Description: List currently defined channels and some information
about them.
Variables:
ActionID: Optional Action id for message matching $cb
—callback ( Connection $conn, array $packet )
- Action: CoreShowChannels
-
void public function status ( callable $cb, string $channel = null )
- Action: Status
Synopsis: Lists channel status
Privilege: system,call,reporting,all
Description: Lists channel status along with requested channel vars.
Variables: (Names marked with * are required)
Channel: Name of the channel to query for status
Variables: Comma ',' separated list of variables to include
ActionID: Optional ID for this transaction
Will return the status information of each channel along with the
value for the specified channel variables $cb
—callback ( Connection $conn, array $packet )
$channel
- Action: Status
-
void public function redirect ( array $params, callable $cb )
- Action: Redirect
Synopsis: Redirect (transfer) a call
Privilege: call,all
Description: Redirect (transfer) a call.
Variables: (Names marked with are required)
Channel: Channel to redirect
ExtraChannel: Second call leg to transfer (optional)
Exten: Extension to transfer to
Context: Context to transfer to
*Priority: Priority to transfer to
ActionID: Optional Action id for message matching $params
$cb
—callback ( Connection $conn, array $packet )
— Callback called when response received
- Action: Redirect
-
void public function originate ( array $params, callable $cb )
- Action: Originate
Synopsis: Originate a call
Privilege: call,all
Description: first the Channel is rung. Then, when that answers, the Extension is dialled within the Context
to initiate the other end of the call.
Variables: (Names marked with are required)
Channel: Channel on which to originate the call (The same as you specify in the Dial application command)
Context: Context to use on connect (must use Exten & Priority with it)
Exten: Extension to use on connect (must use Context & Priority with it)
Priority: Priority to use on connect (must use Context & Exten with it)
Timeout: Timeout (in milliseconds) for the originating connection to happen(defaults to 30000 milliseconds)
CallerID: CallerID to use for the call
Variable: Channels variables to set (max 32). Variables will be set for both channels (local and connected).
Account: Account code for the call
Application: Application to use on connect (use Data for parameters)
Data : Data if Application parameter is used
ActionID: Optional Action id for message matching $params
$cb
—callback ( Connection $conn, array $packet )
— Callback called when response received
- Action: Originate
-
void public function extensionState ( array $params, callable $cb )
- Action: ExtensionState
Synopsis: Get an extension's state.
Description: function can be used to retrieve the state from any hinted extension.
Variables: (Names marked with are required)
Exten: Extension to get state
Context: Context for exten
ActionID: Optional Action id for message matching $params
$cb
—callback ( Connection $conn, array $packet )
— Callback called when response received
- Action: ExtensionState
-
void public function ping ( callable $cb )
- Action: Ping
Description: A 'Ping' action will ellicit a 'Pong' response. Used to keep the
manager connection open.
Variables: NONE $cb
—callback ( Connection $conn, array $packet )
— Callback called when response received
- Action: Ping
-
void public function action ( string $action, callable $cb, array $params = null, array $assertion = null )
- For almost any actions in Action: ListCommands
Privilege: depends on $action $action
— Action$cb
—callback ( Connection $conn, array $packet )
— Callback called when response received$params
— Parameters$assertion
— If more events may follow as response this is a main part or full an action complete event indicating that all data has been sent
- For almost any actions in Action: ListCommands
-
void public function logoff ( callable $cb = null )
- Action: Logoff
Synopsis: Logoff Manager
Privilege:
Description: Logoff this manager session
Variables: NONE $cb
—callback ( Connection $conn, array $packet )
— Optional callback called when response received
- Action: Logoff
-
void public function onEvent ( callable $cb )
- Called when event occured
$cb
— Callback
-
\this public function onConnected ( string|array $event, callable $cb )
- Bind event or events
$event
— Event name$cb
— Callback
namespace PHPDaemon\Clients\Asterisk;
class ConnectionFinished extends \PHPDaemon\Exceptions\ConnectionFinished;
Driver for Asterisk Call Manager/1.1
namespace PHPDaemon\Clients\Asterisk;
class Pool extends \PHPDaemon\Network\Client;
Class Pool
-
authtype (string = 'md5')
Auth hash type port (integer = 5280)
Port
-
array public static $safeCaseValues = [ 0 => 'dialstring', 1 => 'callerid', 2 => 'connectedline', ]
- Beginning of the string in the header or value that indicates whether the save value case
-
void public function setAmiVersion ( string $addr, string $ver )
- Sets AMI version
$addr
— Address$ver
— Version
-
array public static function prepareEnv ( string $data )
- Prepares environment scope
$data
— Address
-
array public static function extract ( string $line )
- Extract key and value pair from line
$line
DNS ← Clients
namespace PHPDaemon\Clients\DNS;
namespace PHPDaemon\Clients\DNS;
class Connection extends \PHPDaemon\Network\ClientConnection;
Constants ← Connection ← DNS ← Clients
-
const STATE_PACKET = 1
- @TODO DESCR
Properties ← Connection ← DNS ← Clients
-
array public $response = [ ]
- Response
Methods ← Connection ← DNS ← Clients
-
void public function onUdpPacket ( string $pct )
- Called when new UDP packet received
$pct
-
void public function onRead ( )
- Called when new data received
-
void public function get ( string $hostname, callable $cb )
- Gets the host information
$hostname
— Hostname$cb
—callback ( )
— Callback
-
void public function onFinish ( )
- Called when connection finishes
namespace PHPDaemon\Clients\DNS;
class Pool extends \PHPDaemon\Network\Client;
-
port (integer = 53)
port -
resolvecachesize (integer = 128)
resolvecachesize -
servers (string = '')
Servers -
hostsfile (string = '/etc/hosts')
hostsfile -
resolvfile (string = '/etc/resolv.conf')
resolvfile expose (boolean = 1)
Expose?
-
array public static $type = [ 1 => 'A', 2 => 'NS', 3 => 'MD', 4 => 'MF', 5 => 'CNAME', 6 => 'SOA', 7 => 'MB', 8 => 'MG', 9 => 'MR', 10 => 'RR', 11 => 'WKS', 12 => 'PTR', 13 => 'HINFO', 14 => 'MINFO', 15 => 'MX', 16 => 'TXT', 17 => 'RP', 18 => 'AFSDB', 19 => 'X25', 20 => 'ISDN', 21 => 'RT', 22 => 'NSAP', 23 => 'NSAP-PTR', 24 => 'SIG', 25 => 'KEY', 26 => 'PX', 27 => 'GPOS', 28 => 'AAAA', 29 => 'LOC', 30 => 'NXT', 31 => 'EID', 32 => 'NIMLOC', 33 => 'SRV', 34 => 'ATMA', 35 => 'NAPTR', 36 => 'KX', 37 => 'CERT', 38 => 'A6', 39 => 'DNAME', 40 => 'SINK', 41 => 'OPT', 42 => 'APL', 43 => 'DS', 44 => 'SSHFP', 45 => 'IPSECKEY', 46 => 'RRSIG', 47 => 'NSEC', 48 => 'DNSKEY', 49 => 'DHCID', 50 => 'NSEC3', 51 => 'NSEC3PARAM', 55 => 'HIP', 99 => 'SPF', 100 => 'UINFO', 101 => 'UID', 102 => 'GID', 103 => 'UNSPEC', 249 => 'TKEY', 250 => 'TSIG', 251 => 'IXFR', 252 => 'AXFR', 253 => 'MAILB', 254 => 'MAILA', 255 => 'ALL', 32768 => 'TA', 32769 => 'DLV', ]
- Record Types [code => "name", ...]
-
array public $hosts = [ ]
- Hosts file parsed [hostname => [addr, ...], ...]
-
\PHPDaemon\Core\ComplexJob public $preloading
- Preloading ComplexJob
-
\CappedStorageHits public $resolveCache
- Resolve cache
-
array public static $class = [ 1 => 'IN', 3 => 'CH', 255 => 'ANY', ]
- Classes [code => "class"]
-
void public function applyConfig ( )
- Applies config
-
void public function resolve ( string $hostname, callable $cb, boolean $noncache = false )
- Resolves the host
$hostname
— Hostname$cb
—callback ( array|string $addrs )
— Callback$noncache
— Noncache?
-
void public function get ( string $hostname, callable $cb, boolean $noncache = false )
- Gets the host information
$hostname
— Hostname$cb
—callback ( )
— Callback$noncache
— Noncache?
Gibson ← Clients
namespace PHPDaemon\Clients\Gibson;
namespace PHPDaemon\Clients\Gibson;
class Connection extends \PHPDaemon\Network\ClientConnection;
Constants ← Connection ← Gibson ← Clients
-
const REPL_ERR = 0x00
- Generic error while executing the query
-
const REPL_ERR_NOT_FOUND = 0x01
- Specified key was not found
-
const REPL_ERR_NAN = 0x02
- Expected a number ( TTL or TIME ) but the specified value was invalid
-
const REPL_ERR_MEM = 0x03
- The server reached configuration memory limit and will not accept any new value until its freeing routine will be executed
-
const REPL_ERR_LOCKED = 0x04
- The specificed key was locked by a OP_LOCK or a OP_MLOCK query
-
const REPL_OK = 0x05
- Query succesfully executed, no data follows
-
const REPL_VAL = 0x06
- Query succesfully executed, value data follows
-
const REPL_KVAL = 0x07
- Query succesfully executed, multiple key => value data follows
-
const STATE_PACKET_HDR = 0x01
-
const STATE_PACKET_DATA = 0x02
-
const GB_ENC_PLAIN = 0x00
- Raw string data follows
-
const GB_ENC_LZF = 0x01
- Compressed data, this is a reserved value not used for replies
-
const GB_ENC_NUMBER = 0x02
- Packed long number follows, four bytes for 32bit architectures, eight bytes for 64bit
Properties ← Connection ← Gibson ← Clients
-
string public $error
- error message
-
public $responseCode
-
public $encoding
-
public $responseLength
-
public $result
-
public $isFinal = false
-
public $totalNum
-
public $readedNum
Methods ← Connection ← Gibson ← Clients
-
void public function onReady ( )
- Called when the connection is handshaked (at low-level), and peer is ready to recv. data
-
boolean public function isFinal ( )
-
integer public function getTotalNum ( )
-
integer public function getReadedNum ( )
-
integer public function getResponseCode ( )
namespace PHPDaemon\Clients\Gibson;
class Pool extends \PHPDaemon\Network\Client;
-
servers (string|array = 'unix:///var/run/gibson.sock')
Default servers -
port (integer = 10128)
Default port -
maxconnperserv (integer = 32)
Maximum connections per server max-allowed-packet (integer = '1M')
Maximum allowed size of packet
-
void public function __call ( string $name, array $args )
- Magic __call
Example:
$gibson->set(3600, 'key', 'value');
$gibson->get('key', function ($conn) {.
..}); $name
— Command name$args
— Arguments
- Magic __call
-
boolean public function isCommand ( string $name )
- Is command?
$name
— Command
HTTP ← Clients
namespace PHPDaemon\Clients\HTTP;
Designed to perform GET and POST requests to remote hosts.
The client uses the namespace HTTPRequest.
Receiving a file google.com/robots.txt GET by request:
$httpclient = \PHPDaemon\Clients\HTTP\Pool::getInstance();
$httpclient->get('http://www.google.com/robots.txt',
function ($conn, $success) {
// response data processing
}
);
A working example of a client is presented in Clients/HTTP/Examples/Simple.php
namespace PHPDaemon\Clients\HTTP;
class Connection extends \PHPDaemon\Network\ClientConnection;
Constants ← Connection ← HTTP ← Clients
-
const STATE_HEADERS = 1
- State: headers
-
const STATE_BODY = 2
- State: body
Properties ← Connection ← HTTP ← Clients
-
array public $headers = [ ]
- Associative array of headers
-
integer public $contentLength = -1
- Content length
-
string public $body = ''
- Contains response body
-
array public $cookie = [ ]
- Associative array of Cookies
-
boolean public $chunked = false
-
callback public $chunkcb
-
integer public $protocolError
-
integer public $responseCode = 0
-
string public $lastURL
- Last requested URL
-
array public $rawHeaders
- Raw headers array
-
public $contentType
-
public $charset
-
public $eofTerminated = false
Methods ← Connection ← HTTP ← Clients
-
void public function get ( string $url, array $params = null )
- Performs GET-request
$url
$params
-
void public function post ( string $url, array $data = [], array $params = null )
- Performs POST-request
$url
$data
$params
-
string public function getBody ( )
- Get body
-
array public function getHeaders ( )
- Get headers
-
string public function getHeader ( string $name )
- Get header
$name
— Header name
-
void public function onRead ( )
- Called when new data received
-
void public function onFinish ( )
- Called when connection finishes
namespace PHPDaemon\Clients\HTTP;
class Pool extends \PHPDaemon\Network\Client;
-
port (integer = 80)
Default port -
sslport (integer = 443)
Default SSL port expose (boolean = 1)
Send User-Agent header?
-#.method ```php:p.inline.wico[data-link=https://github.com/kakserpom/phpdaemon/blob/master/PHPDaemon/Clients/HTTP/Pool.php#L40] ( url $url, array $params ); ( url $url, callable $resultcb );
-.n Performs GET-request
-.n.ti `:hc`$url`
-.n `:hc`$params`
-.n `:hc`$resultcb` — `:phc`callback ( Connection $conn, boolean $success )`
-#.method ```php:p.inline.wico[data-link=https://github.com/kakserpom/phpdaemon/blob/master/PHPDaemon/Clients/HTTP/Pool.php#L77]
( url $url, array $data, array $params );
( url $url, array $data, callable $resultcb );
- Performs HTTP request
$url
$data
$params
-
$resultcb
—callback ( Connection $conn, boolean $success )
-#.method ```php:p.inline.wico[data-link=https://github.com/kakserpom/phpdaemon/blob/master/PHPDaemon/Clients/HTTP/Pool.php#L111] ( string $str ); ( array $mixed );
- Builds URL from array
-
$mixed
-#.method ```php:p.inline.wico[data-link=https://github.com/kakserpom/phpdaemon/blob/master/PHPDaemon/Clients/HTTP/Pool.php#L147] ( string $str ); ( array $mixed );
- Parse URL
$mixed
— Look Pool::buildUrl()
ICMP ← Clients
namespace PHPDaemon\Clients\ICMP;
namespace PHPDaemon\Clients\ICMP;
class Connection extends \PHPDaemon\Network\ClientConnection;
Methods ← Connection ← ICMP ← Clients
-
void public function sendEcho ( callable $cb, string $data = 'phpdaemon' )
- Send echo-request
$cb
—callback ( )
— Callback$data
— Data
-
void public function onRead ( )
- Called when new data received
namespace PHPDaemon\Clients\ICMP;
class Pool extends \PHPDaemon\Network\Client;
-
void public function sendPing ( string $host, callable $cb )
- Establishes connection
$host
— Address$cb
—callback ( )
— Callback
IRC ← Clients
namespace PHPDaemon\Clients\IRC;
namespace PHPDaemon\Clients\IRC;
class Channel extends \PHPDaemon\Structures\ObjectStorage;
-
\Connection public $irc
-
string public $name
-
array public $nicknames = [ ]
-
public $self
-
string public $type
-
string public $topic
-
void public function __construct ( \Connection $irc, string $name )
$irc
$name
-
void public function who ( )
-
void public function onPart ( array|string $mask, mixed $msg = null )
$mask
$msg
-
void public function setChanType ( string $type )
$type
-
array public function exportNicksArray ( )
-
void public function setTopic ( string $msg )
$msg
-
void public function addMode ( string $nick, string $mode )
$nick
$mode
-
void public function removeMode ( string $target, string $mode )
$target
$mode
-
void public function destroy ( )
-
void public function join ( )
-
void public function part ( mixed $msg = null )
$msg
-
$this public function setType ( string $type )
$type
-
void public function detach ( object $obj )
$obj
namespace PHPDaemon\Clients\IRC;
class ChannelParticipant;
Properties ← ChannelParticipant ← IRC ← Clients
-
string public $channel
-
string public $nick
-
string public $user
-
string public $flag
-
string public $mode
-
boolean public $unverified
-
string public $host
Methods ← ChannelParticipant ← IRC ← Clients
-
$this public function setFlag ( string $flag )
$flag
-
void public function __construct ( string $channel, string $nick )
$channel
$nick
-
void public function onModeUpdate ( )
-
$this public function setUser ( string $user )
$user
-
string public function getUsermask ( )
-
$this public function setUnverified ( boolean $bool )
$bool
-
$this public function setHost ( string $host )
$host
-
$this public function setUsermask ( array|string $mask )
$mask
-
static public static function instance ( string $channel, string $nick )
$channel
$nick
-
$this public function setNick ( string $nick )
$nick
-
void public function destroy ( )
-
void public function chanMessage ( string $msg )
$msg
namespace PHPDaemon\Clients\IRC;
class Connection extends \PHPDaemon\Network\ClientConnection;
Properties ← Connection ← IRC ← Clients
-
string public $EOL = '\r\n'
-
string public $nick
-
string public $realname
-
string public $mode = ''
-
array public $buffers = [ ]
-
string public $servername
-
array public $channels = [ ]
-
integer public $latency
-
integer public $lastPingTS
-
integer public $timeout = 300
Methods ← Connection ← IRC ← Clients
-
void public function onReady ( )
- Called when the connection is handshaked (at low-level), and peer is ready to recv. data
-
void public function command ( string $cmd, mixed $args )
$cmd
$args
— Arguments
-
boolean public function commandArr ( integer|string $cmd, array $args = [] )
$cmd
$args
-
void public function join ( array $channels )
$channels
-
void public function part ( array $channels, mixed $msg = null )
$channels
$msg
-
void public function onFinish ( )
- Called when connection finishes
-
void public function ping ( )
-
void public function message ( string $to, string $msg )
$to
$msg
-
void public function addMode ( string $channel, string $target, string $mode )
$channel
$target
$mode
-
void public function removeMode ( string $channel, string $target, string $mode )
$channel
$target
$mode
-
void public function onCommand ( string $from, string $cmd, array $args )
$from
$cmd
$args
-
void public function onRead ( )
- Called when new data received
-
\Channel public function channel ( string $chan )
$chan
-
boolean public function channelIfExists ( string $chan )
$chan
namespace PHPDaemon\Clients\IRC;
class Pool extends \PHPDaemon\Network\Client;
port (integer = 6667)
Port
-
\Pool public $identd
-
boolean public $protologging = false
-
void public function onReady ( )
Lock ← Clients
namespace PHPDaemon\Clients\Lock;
It requires refactoring
namespace PHPDaemon\Clients\Lock;
class Connection extends \PHPDaemon\Network\ClientConnection;
Methods ← Connection ← Lock ← Clients
-
void public function stdin ( string $buf )
- Called when new data received
$buf
— New data
namespace PHPDaemon\Clients\Lock;
class Pool extends \PHPDaemon\Network\Client;
-
servers (string = '127.0.0.1')
default server -
port (string = 833)
default port -
prefix (string = '')
prefix protologging (integer = 0)
protologging
-
void public function job ( string $name, boolean $wait, callable $onRun, callable $onSuccess = NULL, callable $onFailure = NULL )
- Runs a job
$name
— Name of job$wait
— Wait. If true - will wait in queue for lock$onRun
—callback ( )
— Job's runtime$onSuccess
—callback ( )
— Called when job successfully done$onFailure
—callback ( )
— Called when job failed
-
void public function done ( string $name )
- Sends done-event
$name
— Name of job
-
void public function failed ( string $name )
- Sends failed-event
$name
— Name of job
-
boolean public function getConnectionByName ( string $name, callable $cb )
- Returns available connection from the pool by name
$name
— Key$cb
—callback ( )
— Callback
Memcache ← Clients
namespace PHPDaemon\Clients\Memcache;
namespace PHPDaemon\Clients\Memcache;
class Connection extends \PHPDaemon\Network\ClientConnection;
Constants ← Connection ← Memcache ← Clients
-
const STATE_DATA = 1
- DESCR
Properties ← Connection ← Memcache ← Clients
-
mixed public $result
- current result
-
string public $valueFlags
- flags of incoming value
-
integer public $valueLength
- length of incoming value
-
string public $error
- error message
-
string public $key
- current incoming key
namespace PHPDaemon\Clients\Memcache;
class Pool extends \PHPDaemon\Network\Client;
-
servers (string|array = 'tcp://127.0.0.1')
Default servers -
port (integer = 11211)
Default port maxconnperserv (integer = 32)
Maximum connections per server
-
void public function get ( string $key, callable $onResponse )
- Gets the key
$key
— Key$onResponse
—callback ( )
— Callback called when response received
-
void public function set ( string $key, string $value, integer $exp = 0, callable $onResponse = null )
- Sets the key
$key
— Key$value
— Value$exp
— Lifetime in seconds (0 - immortal)$onResponse
—callback ( )
— Callback called when the request complete
-
void public function add ( string $key, string $value, integer $exp = 0, callable $onResponse = null )
- Adds the key
$key
— Key$value
— Value$exp
— Lifetime in seconds (0 - immortal)$onResponse
—callback ( )
— Callback called when the request complete
-
void public function delete ( string $key, callable $onResponse = null, integer $time = 0 )
- Deletes the key
$key
— Key$onResponse
—callback ( )
— Callback called when the request complete$time
— Time to block this key
-
void public function replace ( string $key, string $value, integer $exp = 0, callable $onResponse = null )
- Replaces the key
$key
— Key$value
— Value$exp
— Lifetime in seconds (0 - immortal)$onResponse
—callback ( )
— Callback called when the request complete
-
void public function append ( string $key, string $value, integer $exp = 0, callable $onResponse = null )
- Appends a string to the key's value
$key
— Key$value
— Value$exp
— Lifetime in seconds (0 - immortal)$onResponse
—callback ( )
— Callback called when the request complete
-
void public function prepend ( string $key, string $value, integer $exp = 0, callable $onResponse = null )
- Prepends a string to the key's value
$key
— Key$value
— Value$exp
— Lifetime in seconds (0 - immortal)$onResponse
—callback ( )
— Callback called when the request complete
-
void public function stats ( callable $onResponse, string $server = NULL )
- Gets a statistics
$onResponse
— Callback called when the request complete$server
— Server
Mongo ← Clients
namespace PHPDaemon\Clients\Mongo;
namespace PHPDaemon\Clients\Mongo;
class Collection;
Properties ← Collection ← Mongo ← Clients
-
\Pool public $pool
- Related Pool object
-
string public $name
- Name of collection
Methods ← Collection ← Mongo ← Clients
-
void public function __construct ( string $name, \Pool $pool )
- Contructor of MongoClientAsyncCollection
$name
— Name of collection$pool
— Pool
-
void public function find ( callable $cb, array $p = [] )
- Finds objects in collection
$cb
—callback ( )
— Callback called when response received$p
— Hash of properties (offset, limit, opts, tailable, where, col, fields, sort, hint, explain, snapshot, orderby, parse_oplog)
-
void public function findAll ( callable $cb, array $p = [] )
- Finds objects in collection and fires callback when got all objects
$cb
—callback ( )
— Callback called when response received$p
— Hash of properties (offset, limit, opts, tailable, where, col, fields, sort, hint, explain, snapshot, orderby, parse_oplog)
-
void public function findOne ( callable $cb, array $p = [] )
- Finds one object in collection
$cb
—callback ( )
— Callback called when response received$p
— Hash of properties (offset, opts, where, col, fields, sort, hint, explain, snapshot, orderby, parse_oplog)
-
void public function count ( callable $cb, array $p = [] )
- Counts objects in collection
$cb
—callback ( )
— Callback called when response received$p
— Hash of properties (offset, limit, opts, where, col)
-
void public function ensureIndex ( array $keys, array $options = [], callable $cb = null )
- Ensure index
$keys
— Keys$options
— Optional. Options$cb
—callback ( )
— Optional. Callback called when response received
-
void public function group ( callable $cb, array $p = [] )
- Groupping function
$cb
—callback ( )
— Callback called when response received$p
— Hash of properties (offset, limit, opts, key, col, reduce, initial)
-
\MongoId public function insert ( array $doc, callable $cb = null, array $params = null )
- Inserts an object
$doc
— Data$cb
—callback ( )
— Optional. Callback called when response received$params
— Optional. Params
-
\MongoId public function insertOne ( array $doc, callable $cb = null, array $params = null )
- Inserts an object
$doc
— Data$cb
—callback ( )
— Optional. Callback called when response received$params
— Optional. Params
-
array public function insertMulti ( array $docs, callable $cb = null, array $params = null )
- Inserts several documents
$docs
— Array of docs$cb
—callback ( )
— Optional. Callback called when response received$params
— Optional. Params
-
void public function update ( array $cond, array $data, integer $flags = 0, callable $cb = null, array $params = null )
- Updates one object in collection
$cond
— Conditions$data
— Data$flags
— Optional. Flags$cb
—callback ( )
— Optional. Callback called when response received$params
— Optional. Params
-
void public function updateOne ( array $cond, array $data, callable $cb = null, array $params = null )
- Updates one object in collection
$cond
— Conditions$data
— Data$cb
—callback ( )
— Optional. Callback called when response received$params
— Optional. Params
-
void public function updateMulti ( array $cond, array $data, callable $cb = null, array $params = null )
- Updates one object in collection
$cond
— Conditions$data
— Data$cb
—callback ( )
— Optional. Callback called when response received$params
— Optional. Params
-
void public function upsert ( array $cond, array $data, boolean $multi = false, callable $cb = NULL, array $params = null )
- Upserts an object (updates if exists, insert if not exists)
$cond
— Conditions$data
— Data$multi
— Optional. Multi-flag$cb
—callback ( )
— Optional. Callback called when response received$params
— Optional. Params
-
void public function upsertOne ( array $cond, array $data, callable $cb = NULL, array $params = null )
- Upserts an object (updates if exists, insert if not exists)
$cond
— Conditions$data
— Data$cb
—callback ( )
— Optional. Callback called when response received$params
— Optional. Params
-
void public function upsertMulti ( array $cond, array $data, callable $cb = NULL, array $params = null )
- Upserts an object (updates if exists, insert if not exists)
$cond
— Conditions$data
— Data$cb
—callback ( )
— Optional. Callback called when response received$params
— Optional. Params
-
void public function remove ( array $cond = [], callable $cb = NULL, array $params = null )
- Removes objects from collection
$cond
— Conditions$cb
—callback ( )
— Optional. Callback called when response received$params
— Optional. Params
-
void public function evaluate ( string $code, callable $cb )
- Evaluates a code on the server side
$code
— Code$cb
—callback ( )
— Callback called when response received
-
void public function aggregate ( array $p, callable $cb )
- Aggregate
$p
— Params$cb
—callback ( )
— Callback called when response received
-
void public function autoincrement ( callable $cb, boolean $plain = false )
- Generation autoincrement
$cb
—callback ( )
— Called when response received$plain
— Plain?
-
void public function findAndModify ( array $p, callable $cb )
- Generation autoincrement
$p
— Params$cb
—callback ( )
— Callback called when response received
namespace PHPDaemon\Clients\Mongo;
class Connection extends \PHPDaemon\Network\ClientConnection;
Constants ← Connection ← Mongo ← Clients
-
const STATE_PACKET = 1
- @TODO DESCR
Properties ← Connection ← Mongo ← Clients
-
string public $dbname
- Database name
-
array public $cursors = [ ]
- Active cursors
-
array public $requests = [ ]
- Pending requests
-
integer public $lastReqId = 0
- ID of the last request
Methods ← Connection ← Mongo ← Clients
-
void public function onReady ( )
-
void public function onRead ( )
- Called when new data received
-
void public function onFinish ( )
- onFinish
namespace PHPDaemon\Clients\Mongo;
class ConnectionFinished extends \PHPDaemon\Exceptions\ConnectionFinished;
namespace PHPDaemon\Clients\Mongo;
class Cursor;
-
mixed public $id
- Cursor's ID
-
string public $col
- Collection's name
-
array public $items = [ ]
- Array of objects
-
mixed public $item
- Current object
-
boolean public $finished = false
- Is this cursor finished?
-
boolean public $failure = false
- Is this query failured?
-
boolean public $await = false
- awaitCapable?
-
boolean public $destroyed = false
- Is this cursor destroyed?
-
boolean public $parseOplog = false
-
boolean public $tailable
-
callable public $callback
-
public $counter = 0
-
mixed public function error ( )
- Error
-
void public function keep ( boolean $bool = true )
- Keep
$bool
-
void public function rewind ( )
- Rewind
-
mixed public function current ( )
- Current
-
string public function key ( )
- Key
-
void public function next ( )
- Next
-
array public function grab ( )
- Grab
-
array public function toArray ( )
- To array
-
boolean public function valid ( )
- Valid
-
boolean public function isBusyConn ( )
-
\Connection public function getConn ( )
-
boolean public function isFinished ( )
-
void public function __construct ( string $id, string $col, \Connection $conn )
- Constructor
$id
— Cursor's ID$col
— Collection's name$conn
— Network connection (MongoClientConnection)
-
void public function getMore ( integer $number = 0 )
- Asks for more objects
$number
— Number of objects
-
boolean public function isDead ( )
- isDead
-
boolean public function destroy ( boolean $notify = false )
- Destroys the cursors
$notify
-
boolean public function free ( boolean $notify = false )
- Destroys the cursors
$notify
-
void public function __destruct ( )
- Cursor's destructor. Sends a signal to the server
namespace PHPDaemon\Clients\Mongo;
class MongoId extends \MongoId;
-
mixed public static function import ( mixed $id )
- Import
$id
— ID
-
void public function __construct ( string $id = null )
$id
-
string public function __toString ( )
- __toString
-
string public function toHex ( )
- toHex
-
\MongoId public function getPlainObject ( )
- getPlainObject
namespace PHPDaemon\Clients\Mongo;
class Pool extends \PHPDaemon\Network\Client;
-
servers (string|array = 'tcp://127.0.0.1')
default server list -
port (integer = 27017)
default port maxconnperserv (integer = 32)
maxconnperserv
-
const OP_REPLY = 1
- @TODO DESCR
-
const OP_MSG = 1000
- @TODO DESCR
-
const OP_UPDATE = 2001
- @TODO DESCR
-
const OP_INSERT = 2002
- @TODO DESCR
-
const OP_QUERY = 2004
- @TODO DESCR
-
const OP_GETMORE = 2005
- @TODO DESCR
-
const OP_DELETE = 2006
- @TODO DESCR
-
const OP_KILL_CURSORS = 2007
- @TODO DESCR
-
array public $collections = [ ]
- Objects of MongoClientAsyncCollection
-
string public $dbname = ''
- Current database
-
\Connection public $lastRequestConnection
- Holds last used MongoClientAsyncConnection object
-
object public $cache
- Object of MemcacheClient
-
void public static function safeModeEnc ( array $o )
$o
-
boolean public function selectDB ( string $name )
- Sets default database name
$name
— Database name
-
string public static function getAuthKey ( string $username, string $password, string $nonce )
- Generates auth. key
$username
— Username$password
— Password$nonce
— Nonce
-
void public function addServer ( string $url, integer $weight = NULL, mixed $mock = null )
- Adds mongo server
$url
— URL$weight
— Weight$mock
— @deprecated
-
void public function request ( integer $opcode, string $data, boolean $reply = false, \Connection $conn = null, callable $sentcb = null )
- Gets the key
$opcode
— Opcode (see constants above)$data
— Data$reply
— Is an answer expected?$conn
— Connection. Optional$sentcb
—callback ( )
— Sent callback
-
void public function findAll ( array $p, callable $cb )
- Finds objects in collection and fires callback when got all objects
$p
— Hash of properties (offset, limit, opts, tailable, await, where, col, fields, sort, hint, explain, snapshot, orderby, parse_oplog)$cb
—callback ( )
— Callback called when response received
-
void public function find ( array $p, callable $cb )
- Finds objects in collection
$p
— Hash of properties (offset, limit, opts, tailable, await, where, col, fields, sort, hint, explain, snapshot, orderby, parse_oplog)$cb
—callback ( )
— Callback called when response received
-
void public function findOne ( array $p, callable $cb )
- Finds one object in collection
$p
— Hash of properties (offset, opts, where, col, fields, sort, hint, explain, snapshot, orderby, parse_oplog)$cb
—callback ( )
— Callback called when response received
-
void public function findCount ( array $p, callable $cb )
- Counts objects in collection
$p
— Hash of properties (offset, limit, opts, where, col)$cb
—callback ( )
— Callback called when response received
-
void public function auth ( array $p, callable $cb )
- Sends authenciation packet
$p
— Hash of properties (dbname, user, password, nonce)$cb
—callback ( )
— Callback called when response received
-
void public function getNonce ( array $p, callable $cb )
- Sends request of nonce
$p
— Hash of properties$cb
—callback ( )
— Callback called when response received
-
string public function getIndexName ( array $keys )
$keys
-
void public function ensureIndex ( string $ns, array $keys, array $options = [], callable $cb = null )
- Ensure index
$ns
— Collection$keys
— Keys$options
— Optional. Options$cb
—callback ( )
— Optional. Callback called when response received
-
void public function lastError ( string $db, callable $cb, array $params = [], \Connection $conn = null )
- Gets last error
$db
— Dbname$cb
—callback ( )
— Callback called when response received$params
— Parameters$conn
— Connection. Optional
-
void public function range ( array $p, callable $cb )
- Find objects in collection using min/max specifiers
$p
— Hash of properties (offset, limit, opts, where, col, min, max)$cb
—callback ( )
— Callback called when response received
-
void public function evaluate ( string $code, callable $cb )
- Evaluates a code on the server side
$code
— Code$cb
—callback ( )
— Callback called when response received
-
void public function distinct ( array $p, callable $cb )
- Returns distinct values of the property
$p
— Hash of properties (offset, limit, opts, key, col, where)$cb
—callback ( )
— Callback called when response received
-
void public function findAndModify ( array $p, callable $cb )
- Find and modify
$p
— Hash of properties$cb
—callback ( )
— Callback called when response received
-
void public function group ( array $p, callable $cb )
- Groupping function
$p
— Hash of properties (offset, limit, opts, key, col, reduce, initial)$cb
—callback ( )
— Callback called when response received
-
void public function aggregate ( array $p, callable $cb )
- Aggregate function
$p
— Hash of properties (offset, limit, opts, key, col)$cb
—callback ( )
— Callback called when response received
-
void public function update ( string $col, array $cond, array $data, integer $flags = 0, callable $cb = NULL, array $params = [] )
- Updates one object in collection
$col
— Collection's name$cond
— Conditions$data
— Data$flags
— Optional. Flags$cb
—callback ( )
— Optional. Callback$params
— Optional. Parameters
-
void public function updateOne ( string $col, array $cond, array $data, callable $cb = NULL, array $params = [] )
- Updates one object in collection
$col
— Collection's name$cond
— Conditions$data
— Data$cb
—callback ( )
— Optional. Callback$params
— Optional. Parameters
-
void public function updateMulti ( string $col, array $cond, array $data, callable $cb = NULL, array $params = [] )
- Updates several objects in collection
$col
— Collection's name$cond
— Conditions$data
— Data$cb
—callback ( )
— Optional. Callback$params
— Optional. Parameters
-
void public function upsert ( string $col, array $cond, array $data, boolean $multi = false, callable $cb = NULL, array $params = [] )
- Upserts an object (updates if exists, insert if not exists)
$col
— Collection's name$cond
— Conditions$data
— Data$multi
— Optional. Multi$cb
—callback ( )
— Optional. Callback$params
— Optional. Parameters
-
void public function upsertOne ( string $col, array $cond, array $data, callable $cb = NULL, array $params = [] )
- Upserts an object (updates if exists, insert if not exists)
$col
— Collection's name$cond
— Conditions$data
— Data$cb
—callback ( )
— Optional. Callback$params
— Optional. Parameters
-
void public function upsertMulti ( string $col, array $cond, array $data, callable $cb = NULL, array $params = [] )
- Upserts an object (updates if exists, insert if not exists)
$col
— Collection's name$cond
— Conditions$data
— Data$cb
—callback ( )
— Optional. Callback$params
— Optional. Parameters
-
\MongoId public function insert ( string $col, array $doc = [], callable $cb = NULL, array $params = [] )
- Inserts an object
$col
— Collection's name$doc
— Document$cb
—callback ( )
— Optional. Callback$params
— Optional. Parameters
-
void public function killCursors ( array $cursors = [], \Connection $conn )
- Sends a request to kill certain cursors on the server side
$cursors
— Array of cursors$conn
— Connection
-
array public function insertMulti ( string $col, array $docs = [], callable $cb = NULL, array $params = [] )
- Inserts several documents
$col
— Collection's name$docs
— Array of docs$cb
—callback ( )
— Optional. Callback$params
— Optional. Parameters
-
void public function remove ( string $col, array $cond = [], callable $cb = NULL, array $params = [] )
- Remove objects from collection
$col
— Collection's name$cond
— Conditions$cb
—callback ( )
— Optional. Callback called when response received$params
— Optional. Parameters
-
void public function getMore ( string $col, string $id, integer $number, \Connection $conn )
- Asks for more objects
$col
— Collection's name$id
— Cursor's ID$number
— Number of objects$conn
— Connection
-
\Collection public function getCollection ( string $col )
- Returns an object of collection
$col
— Collection's name
-
\Collection public function __get ( string $name )
- Magic getter-method. Proxy for getCollection
$name
— Collection's name
MySQL ← Clients
namespace PHPDaemon\Clients\MySQL;
Client for the DBMS MySQL
@TODO
In your application, you should receive an object MySQLClient through Daemon::$appResolver->getInstanceByAppName('MySQLClient')
and use as described below.
/*
@method getConnection
@description Establishes connection.
@param string Optional. Address.
@return integer Connection's ID.
*/
You should get MySQLClientSession object by the method $MySQLClient->getConnection(), then you can put your current request / session / anything else in the current context of the connection (in the context property).
Then use:
$this->sql->onConnected(
function($sql, $success) {
if (!$success) {
return;
}
// your connection-dependent code
}
);
$sql->query('SHOW VARIABLES',
function($sql, $success) {
$sql->context->queryResult = $sql->resultRows; // save the result
$sql->context->wakeup(); // wake up the request immediately
}
);
When the callback-function is called, $sql->context contains your subject that you put there before. $sql->resultRows stores the result in an array of associative arrays. $sql->resultFields field contains the response as an array of associative arrays.
namespace PHPDaemon\Clients\MySQL;
class Connection extends \PHPDaemon\Network\ClientConnection;
Constants ← Connection ← MySQL ← Clients
-
const STATE_STANDBY = 0
- @TODO DESCR
-
const STATE_BODY = 1
- @TODO DESCR
-
const PHASE_GOT_INIT = 1
- @TODO DESCR
-
const PHASE_AUTH_SENT = 2
- @TODO DESCR
-
const PHASE_AUTH_ERR = 3
- @TODO DESCR
-
const PHASE_HANDSHAKED = 4
- @TODO DESCR
-
const RS_STATE_HEADER = 0
- @TODO DESCR
-
const RS_STATE_FIELD = 1
- @TODO DESCR
-
const RS_STATE_ROW = 2
- @TODO DESCR
Properties ← Connection ← MySQL ← Clients
-
integer public $seq = 0
- Sequence. Pointer of packet sequence
-
integer public $clientFlags = 239237
- Client flags
-
integer public $threadId
-
string public $scramble
-
string public $serverver
-
integer public $serverCaps
-
integer public $serverLang
-
integer public $serverStatus
- Server flags: http://dev.mysql.com/doc/internals/en/status-flags.html
-
integer public $warnCount
- Number of warnings generated by the command
-
string public $message
-
integer public $charsetNumber = 33
- Charset number (see MySQL charset list)
-
string public $dbname = ''
- Database name
-
array public $resultRows = [ ]
- Result rows
-
array public $resultFields = [ ]
- Result fields
-
object public $context
- Property holds a reference to user's object
-
integer public $insertId
- INSERT_ID()
-
integer public $affectedRows
- Affected rows
-
integer public $protover = 0
- Protocol version
-
integer public $timeout = 120
- Timeout
-
integer public $errno = 0
- Error number
-
string public $errmsg = ''
- Error message
Methods ← Connection ← MySQL ← Clients
-
void public function onConnected ( callable $cb )
- Executes the given callback when/if the connection is handshaked
$cb
—callback ( Connection $conn, boolean $success )
— Callback
-
void public function onReady ( )
- Called when the connection is handshaked (at low-level), and peer is ready to recv. data
-
boolean public function sendPacket ( string $packet )
- Sends a packet
$packet
— Data
-
string public function buildLenEncodedBinary ( string $s )
- Builds length-encoded binary string
$s
— String
-
integer public function parseEncodedBinary ( )
- Parses length-encoded binary integer
-
integer public function parseEncodedString ( )
- Parse length-encoded string
-
string public function getAuthToken ( string $scramble, string $password )
- Generates auth. token
$scramble
— Scramble string$password
— Password
-
void public function auth ( )
- Sends auth. packet
-
boolean public function query ( string $q, callable $callback = NULL )
- Sends SQL-query
$q
— Query$callback
—callback ( Connection $conn, boolean $success )
— Optional. Callback called when response received
-
boolean public function ping ( callable $callback = NULL )
- Sends echo-request
$callback
—callback ( Connection $conn, boolean $success )
— Optional. Callback called when response received
-
boolean public function command ( string $cmd, string $q = '', callable $callback = NULL )
- Sends arbitrary command
$cmd
— Command$q
— Data$callback
—callback ( Connection $conn, boolean $success )
— Optional
-
boolean public function selectDB ( string $name )
- Sets default database name
$name
— Database name
-
void public function onRead ( )
- Called when new data received
-
void public function onResultDone ( )
- Called when the whole result received
-
void public function onError ( )
- Called when error occured
namespace PHPDaemon\Clients\MySQL;
class ConnectionFinished extends \PHPDaemon\Exceptions\ConnectionFinished;
namespace PHPDaemon\Clients\MySQL;
class Pool extends \PHPDaemon\Network\Client;
-
server (array|string = 'tcp://[email protected]/')
@todo -
port (integer = 3306)
@todo maxconnperserv (integer = 32)
@todo
-
const CLIENT_LONG_PASSWORD = 1
- new more secure passwords
-
const CLIENT_FOUND_ROWS = 2
- Found instead of affected rows
-
const CLIENT_LONG_FLAG = 4
- Get all column flags
-
const CLIENT_CONNECT_WITH_DB = 8
- One can specify db on connect
-
const CLIENT_NO_SCHEMA = 16
- Don't allow database.table.column
-
const CLIENT_COMPRESS = 32
- Can use compression protocol
-
const CLIENT_ODBC = 64
- Odbc client
-
const CLIENT_LOCAL_FILES = 128
- Can use LOAD DATA LOCAL
-
const CLIENT_IGNORE_SPACE = 256
- Ignore spaces before '('
-
const CLIENT_PROTOCOL_41 = 512
- New 4.1 protocol
-
const CLIENT_INTERACTIVE = 1024
- This is an interactive client
-
const CLIENT_SSL = 2048
- Switch to SSL after handshake
-
const CLIENT_IGNORE_SIGPIPE = 4096
- IGNORE sigpipes
-
const CLIENT_TRANSACTIONS = 8192
- Client knows about transactions
-
const CLIENT_RESERVED = 16384
- Old flag for 4.1 protocol
-
const CLIENT_SECURE_CONNECTION = 32768
- New 4.1 authentication
-
const CLIENT_MULTI_STATEMENTS = 65536
- Enable/disable multi-stmt support
-
const CLIENT_MULTI_RESULTS = 131072
- Enable/disable multi-results
-
const COM_SLEEP = 0x00
- (none, this is an internal thread state)
-
const COM_QUIT = 0x01
- mysql_close
-
const COM_INIT_DB = 0x02
- mysql_select_db
-
const COM_QUERY = 0x03
- mysql_real_query
-
const COM_FIELD_LIST = 0x04
- mysql_list_fields
-
const COM_CREATE_DB = 0x05
- mysql_create_db (deprecated)
-
const COM_DROP_DB = 0x06
- mysql_drop_db (deprecated)
-
const COM_REFRESH = 0x07
- mysql_refresh
-
const COM_SHUTDOWN = 0x08
- mysql_shutdown
-
const COM_STATISTICS = 0x09
- mysql_stat
-
const COM_PROCESS_INFO = 0x0a
- mysql_list_processes
-
const COM_CONNECT = 0x0b
- (none, this is an internal thread state)
-
const COM_PROCESS_KILL = 0x0c
- mysql_kill
-
const COM_DEBUG = 0x0d
- mysql_dump_debug_info
-
const COM_PING = 0x0e
- mysql_ping
-
const COM_TIME = 0x0f
- (none, this is an internal thread state)
-
const COM_DELAYED_INSERT = 0x10
- (none, this is an internal thread state)
-
const COM_CHANGE_USER = 0x11
- mysql_change_user
-
const COM_BINLOG_DUMP = 0x12
- sent by the slave IO thread to request a binlog
-
const COM_TABLE_DUMP = 0x13
- LOAD TABLE ... FROM MASTER (deprecated)
-
const COM_CONNECT_OUT = 0x14
- (none, this is an internal thread state)
-
const COM_REGISTER_SLAVE = 0x15
- sent by the slave to register with the master (optional)
-
const COM_STMT_PREPARE = 0x16
- mysql_stmt_prepare
-
const COM_STMT_EXECUTE = 0x17
- mysql_stmt_execute
-
const COM_STMT_SEND_LONG_DATA = 0x18
- mysql_stmt_send_long_data
-
const COM_STMT_CLOSE = 0x19
- mysql_stmt_close
-
const COM_STMT_RESET = 0x1a
- mysql_stmt_reset
-
const COM_SET_OPTION = 0x1b
- mysql_set_server_option
-
const COM_STMT_FETCH = 0x1c
- mysql_stmt_fetch
-
const FIELD_TYPE_DECIMAL = 0x00
-
const FIELD_TYPE_TINY = 0x01
-
const FIELD_TYPE_SHORT = 0x02
-
const FIELD_TYPE_LONG = 0x03
-
const FIELD_TYPE_FLOAT = 0x04
-
const FIELD_TYPE_DOUBLE = 0x05
-
const FIELD_TYPE_NULL = 0x06
-
const FIELD_TYPE_TIMESTAMP = 0x07
-
const FIELD_TYPE_LONGLONG = 0x08
-
const FIELD_TYPE_INT24 = 0x09
-
const FIELD_TYPE_DATE = 0x0a
-
const FIELD_TYPE_TIME = 0x0b
-
const FIELD_TYPE_DATETIME = 0x0c
-
const FIELD_TYPE_YEAR = 0x0d
-
const FIELD_TYPE_NEWDATE = 0x0e
-
const FIELD_TYPE_VARCHAR = 0x0f
-
const FIELD_TYPE_BIT = 0x10
-
const FIELD_TYPE_NEWDECIMAL = 0xf6
-
const FIELD_TYPE_ENUM = 0xf7
-
const FIELD_TYPE_SET = 0xf8
-
const FIELD_TYPE_TINY_BLOB = 0xf9
-
const FIELD_TYPE_MEDIUM_BLOB = 0xfa
-
const FIELD_TYPE_LONG_BLOB = 0xfb
-
const FIELD_TYPE_BLOB = 0xfc
-
const FIELD_TYPE_VAR_STRING = 0xfd
-
const FIELD_TYPE_STRING = 0xfe
-
const FIELD_TYPE_GEOMETRY = 0xff
-
const NOT_NULL_FLAG = 0x1
-
const PRI_KEY_FLAG = 0x2
-
const UNIQUE_KEY_FLAG = 0x4
-
const MULTIPLE_KEY_FLAG = 0x8
-
const BLOB_FLAG = 0x10
-
const UNSIGNED_FLAG = 0x20
-
const ZEROFILL_FLAG = 0x40
-
const BINARY_FLAG = 0x80
-
const ENUM_FLAG = 0x100
-
const AUTO_INCREMENT_FLAG = 0x200
-
const TIMESTAMP_FLAG = 0x400
-
const SET_FLAG = 0x800
-
string public static function escape ( string $string )
- Escapes the special symbols with trailing backslash
$string
-
string public static function value ( mixed $mixed )
- [value description]
$mixed
-
string public static function values ( array $arr )
- [values description]
$arr
-
string public static function likeEscape ( string $string )
- Escapes the special symbols with a trailing backslash
$string
PostgreSQL ← Clients
namespace PHPDaemon\Clients\PostgreSQL;
Connection ← PostgreSQL ← Clients
namespace PHPDaemon\Clients\PostgreSQL;
class Connection extends \PHPDaemon\Network\ClientConnection;
Constants ← Connection ← PostgreSQL ← Clients
-
const STATE_AUTH_PACKET_SENT = 2
- State: authentication packet sent
-
const STATE_AUTH_ERROR = 3
- State: authencation error
-
const STATE_AUTH_OK = 4
- State: authentication passed
Properties ← Connection ← PostgreSQL ← Clients
-
string public $protover = '3.0'
- Protocol version
-
integer public $maxPacketSize = 16777216
- Maximum packet size
-
integer public $charsetNumber = 8
- Charset number
-
string public $dbname = ''
- Database name
-
string public $options = ''
- Default options
-
integer public $state = 0
- Connection's state. 0 - start, 1 - got initial packet, 2 - auth. packet sent, 3 - auth. error, 4 - handshaked OK
-
string public $instate = 0
- State of pointer of incoming data. 0 - Result Set Header Packet, 1 - Field Packet, 2 - Row Packet
-
array public $resultRows = [ ]
- Resulting rows
-
array public $resultFields = [ ]
- Resulting fields
-
string public $insertId
- Equals to INSERT_ID()
-
integer public $insertNum
- Inserted rows number
-
integer public $affectedRows
- Number of affected rows
-
array public $parameters = [ ]
- Runtime parameters from server
-
string public $backendKey
- Backend key
Methods ← Connection ← PostgreSQL ← Clients
-
void public function onReady ( )
- Called when the connection is ready to accept new data
-
void public function onConnected ( callable $cb )
- Executes the given callback when/if the connection is handshaked
$cb
—callback ( )
— Callback
-
integer public function bytes2int ( string $str, boolean $l = TRUE )
- Converts binary string to integer
$str
— Binary string$l
— Optional. Little endian. Default value - true
-
string function int2bytes ( integer $len, integer $int = 0, boolean $l = TRUE )
- Converts integer to binary string
$len
— Length$int
— Integer$l
— Optional. Little endian. Default value - true
-
boolean public function sendPacket ( string $type = '', string $packet )
- Send a packet
$type
— Data$packet
— Packet
-
string public function buildLenEncodedBinary ( string $s )
- Builds length-encoded binary string
$s
— String
-
integer public function parseEncodedBinary ( string &$s, integer &$p )
- Parses length-encoded binary
&$s
— Reference to source string&$p
-
integer public function parseEncodedString ( string &$s, integer &$p )
- Parse length-encoded string
&$s
— Reference to source string&$p
— Reference to pointer
-
boolean public function query ( string $q, callable $callback = NULL )
- Send SQL-query
$q
— Query$callback
—callback ( )
— Optional. Callback called when response received
-
boolean public function ping ( callable $callback = NULL )
- Send echo-request
$callback
—callback ( )
— Optional. Callback called when response received
-
boolean public function sync ( callable $cb = NULL )
- Sends sync-request
$cb
—callback ( )
— Optional. Callback called when response received
-
boolean public function terminate ( callable $cb = NULL )
- Send terminate-request to shutdown the connection
$cb
—callback ( )
— Optional. Callback called when response received
-
boolean public function command ( integer $cmd, string $q = '', callable $cb = NULL )
- Sends arbitrary command
$cmd
— Command's code. See constants above$q
— Data$cb
—callback ( )
— Optional. Callback called when response received
-
boolean public function selectDB ( string $name )
- Set default database name
$name
— Database name
-
void public function stdin ( string $buf )
- Called when new data received
$buf
— New data
-
array public function decodeNULstrings ( string $data, integer $limit = 1, \reference &$p )
- Decode strings from the NUL-terminated representation
$data
— Binary data$limit
— Optional. Limit of count. Default is 1&$p
— Optional. Pointer
-
void public function onResultDone ( )
- Called when the whole result received
-
void public function onError ( )
- Called when error occured
ConnectionFinished ← PostgreSQL ← Clients
namespace PHPDaemon\Clients\PostgreSQL;
class ConnectionFinished extends \PHPDaemon\Exceptions\ConnectionFinished;
Pool ← PostgreSQL ← Clients
namespace PHPDaemon\Clients\PostgreSQL;
class Pool extends \PHPDaemon\Network\Client;
Options ← Pool ← PostgreSQL ← Clients
-
server (array|string = 'tcp://[email protected]')
default server -
port (integer = 5432)
default port -
protologging (integer = 0)
@todo enable (integer = 0)
disabled by default
Redis ← Clients
namespace PHPDaemon\Clients\Redis;
namespace PHPDaemon\Clients\Redis;
class Connection extends \PHPDaemon\Network\ClientConnection;
Constants ← Connection ← Redis ← Clients
-
const STATE_BINARY = 1
- In the middle of binary response part
Properties ← Connection ← Redis ← Clients
-
array|null public $result
- Current result
-
string public $error
- Current error message
-
array public $subscribeCb = [ ]
- Subcriptions
-
public $psubscribeCb = [ ]
Methods ← Connection ← Redis ← Clients
-
\Lock public function lock ( string $key, integer $timeout )
$key
$timeout
-
\MultiEval public function meval ( callable $cb = null )
- Easy wrapper for queue of eval's
$cb
-
integer public function getLocalSubscribersCount ( string $chan )
$chan
-
void public function onReady ( )
- Called when the connection is handshaked (at low-level), and peer is ready to recv. data
-
void public function subscribed ( )
-
boolean public function isSubscribed ( )
-
void public function __call ( \sting $cmd, array $args )
- Magic __call
Example:
$redis->lpush('mylist', microtime(true)); $cmd
$args
- Magic __call
-
void public function command ( string $name, array $args, callable $cb = null )
$name
$args
$cb
—callback ( )
-
void public function sendCommand ( string $name, array $args, callable $cb = null )
$name
$args
$cb
—callback ( )
-
void public function onFinish ( )
- Called when connection finishes
-
void public function pushValue ( mixed $val )
$val
-
void public function pushLevel ( integer $length )
$length
-
void public function checkFree ( )
- Set connection free/busy according to onResponse emptiness and ->finished
namespace PHPDaemon\Clients\Redis;
class Lock;
-
void public function __construct ( string $key, integer $timeout, \Pool $pool )
- Constructor
$key
$timeout
$pool
-
\this public function timeout ( integer $timeout )
$timeout
-
\this public function acquire ( callable $cb )
$cb
—callback ( )
-
\this public function release ( callable $cb = null )
$cb
—callback ( )
namespace PHPDaemon\Clients\Redis;
class MultiEval;
Easy wrapper for queue of eval's
-
array public $listeners = [ ]
- Listeners
-
void public function __construct ( callable $cb, \Pool $pool )
- Constructor
$cb
— Callback$pool
— Redis pool
-
void public function addListener ( callable $cb )
- Adds listener
$cb
-
void public function add ( string $cmd, mixed $keys = null, mixed $argv = null )
- Adds eval command in stack
$cmd
— Lua script$keys
— Keys$argv
— Arguments
-
void public function cleanup ( )
- Clean up
-
array public function getParams ( )
- Return params for eval command
-
void public function execute ( )
- Runs the stack of commands
-
void public function __invoke ( )
- Adds eval command or calls execute() method
namespace PHPDaemon\Clients\Redis;
class Pool extends \PHPDaemon\Network\Client;
-
servers (string|array = 'tcp://127.0.0.1')
Default servers -
port (integer = 6379)
Default port -
maxconnperserv (integer = 32)
Maximum connections per server -
max-allowed-packet (integer = '1M')
Maximum allowed size of packet -
log-pub-sub-race-condition (boolean = true)
If true, race condition between UNSUBSCRIBE and PUBLISH will be journaled -
select (integer = null)
Select storage number sentinel-master (integer = null)
for Sentinel
-
public $servConnSub = [ ]
-
\Lock public function lock ( string $key, integer $timeout )
$key
$timeout
-
\MultiEval public function meval ( callable $cb = null )
- Easy wrapper for queue of eval's
$cb
-
void public function detachConnFromUrl ( \ClientConnection $conn, string $url )
- Detaches connection from URL
$conn
— Connection$url
— URL
-
integer public function getLocalSubscribersCount ( string $chan )
$chan
-
void public function __call ( string $name, array $args )
- Magic __call
Example:
$redis->lpush('mylist', microtime(true)); $name
— Command name$args
— Arguments
- Magic __call
Valve ← Clients
namespace PHPDaemon\Clients\Valve;
namespace PHPDaemon\Clients\Valve;
class Connection extends \PHPDaemon\Network\ClientConnection;
Properties ← Connection ← Valve ← Clients
-
integer public $timeout = 1
- Timeout
Methods ← Connection ← Valve ← Clients
-
void public function requestPlayers ( callable $cb )
- Sends a request of type 'players'
$cb
—callback ( )
— Callback
-
void public function requestInfo ( callable $cb )
- Sends a request of type 'info'
$cb
—callback ( )
— Callback
-
void public function request ( string $type, string $data = null, callable $cb = null )
- Sends a request
$type
— Type of request$data
— Data$cb
—callback ( )
— Callback
-
array public static function parsePlayers ( string &$st )
- Parses response to 'players' command into structure
&$st
— Data
-
array public static function parseInfo ( string &$st, string $type )
- Parses response to 'info' command into structure
&$st
— Data$type
— Type of request
namespace PHPDaemon\Clients\Valve;
class Pool extends \PHPDaemon\Network\Client;
-
servers (string|array = '127.0.0.1')
Default servers -
port (integer = 27015)
Default port maxconnperserv (integer = 32)
Maximum connections per server
-
const A2S_INFO = "\x54"
-
const S2A_INFO = "\x49"
-
const S2A_INFO_SOURCE = "\x6d"
-
const A2S_PLAYER = "\x55"
-
const S2A_PLAYER = "\x44"
-
const A2S_SERVERQUERY_GETCHALLENGE = "\x57"
-
const S2A_SERVERQUERY_GETCHALLENGE = "\x41"
-
const A2A_PING = "\x69"
-
const S2A_PONG = "\x6A"
-
void public function request ( string $addr, string $type, string $data, callable $cb )
- Sends a request
$addr
— Address$type
— Type of request$data
— Data$cb
—callback ( )
— Callback
-
void public function ping ( string $addr, callable $cb )
- Sends echo-request
$addr
— Address$cb
—callback ( )
— Callback
-
void public function requestInfo ( string $addr, callable $cb )
- Sends a request of type 'info'
$addr
— Address$cb
—callback ( )
— Callback
-
void public function requestPlayers ( string $addr, callable $cb )
- Sends a request of type 'players'
$addr
— Address$cb
—callback ( )
— Callback
WebSocket ← Clients
namespace PHPDaemon\Clients\WebSocket;
namespace PHPDaemon\Clients\WebSocket;
class Connection extends \PHPDaemon\Network\ClientConnection;
Class Connection
Constants ← Connection ← WebSocket ← Clients
-
const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
- Globally Unique Identifier @see http://tools.ietf.org/html/rfc6455
-
const STATE_HEADER = 1
-
const STATE_DATA = 2
Properties ← Connection ← WebSocket ← Clients
-
array public $headers = [ ]
-
string public $type
Methods ← Connection ← WebSocket ← Clients
-
void public function onReady ( )
- Called when the connection is handshaked (at low-level), and peer is ready to recv. data
-
void public function onRead ( )
- Called when new data received
-
void public function sendFrame ( string $payload, string $type = Pool::TYPE_TEXT, boolean $isMasked = true )
- Send frame to WebSocket server
$payload
$type
$isMasked
-
void public function onFinish ( )
namespace PHPDaemon\Clients\WebSocket;
class Pool extends \PHPDaemon\Network\Client;
max-allowed-packet (Size = '1M')
Maximum allowed size of packet
-
const TYPE_TEXT = 'text'
- Types of WebSocket frame
-
const TYPE_BINARY = 'binary'
-
const TYPE_CLOSE = 'close'
-
const TYPE_PING = 'ping'
-
const TYPE_PONG = 'pong'
-
void public function getConfigDefaults ( )
XMPP ← Clients
namespace PHPDaemon\Clients\XMPP;
namespace PHPDaemon\Clients\XMPP;
class Connection extends \PHPDaemon\Network\ClientConnection;
Properties ← Connection ← XMPP ← Clients
-
boolean public $use_encryption = false
-
boolean public $authorized
-
integer public $lastId = 0
-
\XMPPRoster public $roster
-
\XMLStream public $xml
-
string public $fulljid
-
integer|string public $keepaliveTimer
- Timer ID
Methods ← Connection ← XMPP ← Clients
-
string public function getId ( )
- Get next ID
-
void public function onReady ( )
- Called when the connection is handshaked (at low-level), and peer is ready to recv. data
-
void public function onFinish ( )
- Called when session finishes
-
void public function sendXML ( string $s )
$s
-
void public function startXMLStream ( )
-
boolean public function iqSet ( string $xml, callable $cb )
$xml
$cb
—callback ( )
-
boolean public function iqSetTo ( string $to, string $xml, callable $cb )
$to
$xml
$cb
—callback ( )
-
boolean public function iqGet ( string $xml, callable $cb )
$xml
$cb
—callback ( )
-
boolean public function iqGetTo ( string $to, string $xml, callable $cb )
$to
$xml
$cb
—callback ( )
-
boolean public function ping ( string $to = null, callable $cb = null )
$to
$cb
—callback ( )
-
boolean public function queryGet ( string $ns, callable $cb )
$ns
$cb
—callback ( )
-
boolean public function querySet ( string $ns, string $xml, callable $cb )
$ns
$xml
$cb
—callback ( )
-
boolean public function querySetTo ( string $to, string $ns, string $xml, callable $cb )
$to
$ns
$xml
$cb
—callback ( )
-
void public function createXMLStream ( )
-
void public function message ( string $to, string $body, string $type = 'chat', string $subject = null )
- Send XMPP Message
$to
$body
$type
$subject
-
void public function presence ( string $status = null, string $show = 'available', string $to = null, string $type = 'available', integer $priority = 0 )
- Set Presence
$status
$show
$to
$type
$priority
-
void public function getVCard ( string $jid = null, callable $cb )
$jid
$cb
—callback ( )
-
void public function onRead ( )
- Called when new data received
namespace PHPDaemon\Clients\XMPP;
class XMPPRoster;
Properties ← XMPPRoster ← XMPP ← Clients
-
\Connection public $xmpp
-
array public $roster_array = [ ]
-
boolean public $track_presence = true
-
boolean public $auto_subscribe = true
-
string public $ns = 'jabber:iq:roster'
Methods ← XMPPRoster ← XMPP ← Clients
-
void public function __construct ( \Connection $xmpp )
- Constructor
$xmpp
-
void public function rosterSet ( string $xml, callable $cb = null )
$xml
$cb
—callback ( )
-
void public function setSubscription ( string $jid, string $type, callable $cb = null )
$jid
$type
$cb
—callback ( )
-
void public function fetch ( callable $cb = null )
$cb
—callback ( )
-
void public function _addContact ( string $jid, string $subscription, string $name = '', array $groups = [] )
- Add given contact to roster
$jid
$subscription
$name
$groups
-
array|null public function getContact ( string $jid )
- Retrieve contact via jid
$jid
-
boolean public function isContact ( string $jid )
- Discover if a contact exists in the roster via jid
$jid
-
void public function setPresence ( string $presence, integer $priority, string $show, string $status )
- Set presence
$presence
$priority
$show
$status
-
array|false public function getPresence ( string $jid )
- Return best presence for jid
$jid
namespace PHPDaemon\Clients\XMPP;
class Pool extends \PHPDaemon\Network\Client;
port (integer = 5222)
Default port
Libraries
Cache ← Libraries
namespace PHPDaemon\Cache;
Local LRU key-value cache mechanism.
It is used to cache shortcuts created via create_function. Also used in Clients\DNS.
namespace PHPDaemon\Cache;
class CappedStorageHits extends \PHPDaemon\Cache\CappedStorage;
CappedStorageHits
Methods ← CappedStorageHits ← Cache ← Libraries
-
void public function __construct ( integer $max = null )
- Constructor
$max
— Maximum number of cached elements
namespace PHPDaemon\Cache;
class Item;
Item
-
integer public $hits = 1
- Hits counter
-
integer public $expire
- Expire time
-
void public function __construct ( )
- Constructor
-
integer public function getHits ( )
- Get hits number
-
mixed public function getValue ( )
- Get value
-
void public function addListener ( callable $cb )
- Adds listener callback
$cb
-
void public function setValue ( mixed $value )
- Sets the value
$value
namespace PHPDaemon\Cache;
class CappedStorage;
CappedStorage
Properties ← CappedStorage ← Cache ← Libraries
-
callable public $sorter
- Sorter function
-
integer public $maxCacheSize = 64
- Maximum number of cached elements
-
integer public $capWindow = 16
- Additional window to decrease number of sorter calls
-
array public $cache = [ ]
- Storage of cached items
Methods ← CappedStorage ← Cache ← Libraries
-
void public function setMaxCacheSize ( integer $size )
- Sets cache size
$size
— Maximum number of elements
-
void public function setCapWindow ( integer $w )
- Sets cap window
$w
— Additional window to decrease number of sorter calls
-
integer public function hash ( string $key )
- Hash function
$key
— Key
-
mixed public function put ( string $key, mixed $value, integer $ttl = null )
- Puts element in cache
$key
— Key$value
— Value$ttl
— Time to live
-
void public function invalidate ( string $key )
- Invalidates cache element
$key
— Key
-
object public function get ( string $key )
- Gets element by key
$key
— Key
-
mixed public function getValue ( string $key )
- Gets value of element by key
$key
— Key
ComplexJob ← Libraries
namespace PHPDaemon\Core;
class ComplexJob extends \ArrayAccess;
ComplexJob class object allows you to hang up the callback function for the completion of all announced it procedures. This is useful when you need to perform a number of independent chains of action.
Примеры ← ComplexJob ← Libraries
$j = new ComplexJob(function($j) { // Когда всё выполнилось
D($j['foo']); // this
D($j['foobar']); // is
D($j['bar']); // sparta
});
/* Add a Task */
$j('foo', function($name, $j) {
$j[$name] = 'this'; // Call setResult()
/* Another Problem */
$j('foobar', function($name, $j) {
$j[$name] = 'is';
});
});
/* And Another */
$j('bar', function($name, $j) {
$j[$name] = 'sparta';
});
$j(); // Run
Constants ← ComplexJob ← Libraries
-
const STATE_WAITING = 1
- State: waiting
-
const STATE_RUNNING = 2
- State: running
-
const STATE_DONE = 3
- State: done
Properties ← ComplexJob ← Libraries
-
array public $listeners = [ ]
- Listeners [callable, ...]
-
array public $results = [ ]
- Hash of results [jobname -> result, ...]
-
integer public $state
- Current state
-
array public $jobs = [ ]
- Hash of jobs [jobname -> callback, ...]
-
integer public $resultsNum = 0
- Number of results
-
integer public $jobsNum = 0
- Number of jobs
Methods ← ComplexJob ← Libraries
-
void public function __construct ( callable $cb = null )
- Constructor
$cb
— Listener
-
boolean public function offsetExists ( string $j )
- Handler of isset($job[$name])
$j
— Job name
-
mixed public function offsetGet ( string $j )
- Handler of $job[$name]
$j
— Job name
-
void public function offsetSet ( string $j, mixed $v )
- Handler of $job[$name] = $value
$j
— Job name$v
— Job result
-
void public function offsetUnset ( string $j )
- Handler of unset($job[$name])
$j
— Job name
-
array public function getResults ( )
- Returns associative array of results
-
void public function keep ( boolean $keep = true )
- Keep
$keep
— Keep?
-
boolean public function hasCompleted ( )
- Has completed?
-
\this public function maxConcurrency ( integer $n = -1 )
- Sets a limit of simultaneously executing tasks
$n
— Natural number or -1 (no limit)
-
boolean public function setResult ( string $jobname, mixed $result = null )
- Set result
$jobname
— Job name$result
— Result
-
mixed public function getResult ( string $jobname )
- Get result
$jobname
— Job name
-
void public function checkQueue ( )
- Called automatically. Checks whether if the queue is full. If not, tries to pull more jobs from backlog and 'more'
-
\this public function more ( callable $cb = null )
- Sets a callback which is going to be fired always when we have a room for more jobs
$cb
— Callback
-
boolean public function isQueueFull ( )
- Returns whether or not the queue is full (maxConcurrency option exceed)
-
boolean public function addJob ( string $name, callable $cb )
- Adds job
$name
— Job name$cb
— Callback
-
void public function cleanup ( )
- Clean up
-
void public function addListener ( callable $cb )
- Adds listener
$cb
— Callback
-
void public function execute ( )
- Runs the job
-
void public function __invoke ( mixed $name = null, callable $cb = null )
- Adds new job or calls execute() method
$name
$cb
ShellCommand ← Libraries
namespace PHPDaemon\Core;
class ShellCommand extends \PHPDaemon\Network\IOStream;
Class is the successor IOStream, so that there are available methods such as read[ln], write[ln], and so on.
Examples ← ShellCommand ← Libraries
Easily perform analogue functions shell_exec
← ShellCommand ← Libraries
shell_exec
← ShellCommand ← LibrariesShellCommand::exec('echo "foo"', function($commandInstance, $output) {
D($output); // foo
});
With additional parameters and environment variables ← Easily perform analogue functions shell_exec
← ShellCommand ← Libraries
shell_exec
← ShellCommand ← Libraries$command = 'git log';
$cb = function($commandInstance, $output) {
D($output); // foo
};
$arguments = ['-1', '--pretty' => 'oneline'];
$env = [];
ShellCommand::exec($command, $cb, $arguments, $env);
Arguments will be screened using
escapeshellarg
Batch Output
@TODO
Properties ← ShellCommand ← Libraries
-
string public $binPath
- Executable path
-
string public $setUser
- SUID
-
string public $setGroup
- SGID
-
string public $chroot = '/'
- Chroot
-
string public $cwd
- Chdir
Methods ← ShellCommand ← Libraries
-
string public function getCmd ( )
- Get command string
-
\this public function setGroup ( )
- Set group
-
\this public function setCwd ( string $dir )
- Set cwd
$dir
-
\this public function setUser ( string $val )
- Set group
$val
-
\this public function setChroot ( string $dir )
- Set chroot
$dir
-
void public static function exec ( string $binPath = null, callable $cb = null, array $args = null, array $env = null )
- Execute
$binPath
— Binpath$cb
— Callback$args
— Optional. Arguments$env
— Optional. Hash of environment's variables
-
void public function setFd ( resource $fd, \EventBufferEvent $bev = null )
- Sets fd
$fd
— File descriptor$bev
-
\this public function setArgs ( array )
- Sets an array of arguments
Arguments
-
\this public function setEnv ( array )
- Set a hash of environment's variables
Hash of environment's variables
-
void public function onEofEvent ( )
- Called when got EOF
-
\this public function nice ( integer $nice = NULL )
- Set priority
$nice
— Priority
-
string public static function buildArgs ( array $args )
- Build arguments string from associative/enumerated array (may be mixed)
$args
-
\this public function execute ( string $binPath = NULL, array $args = NULL, array $env = NULL )
- Execute
$binPath
— Optional. Binpath$args
— Optional. Arguments$env
— Optional. Hash of environment's variables
-
boolean public function finishWrite ( )
- Finish write stream
-
void public function close ( )
- Close the process
-
void public function onFinish ( )
- Called when stream is finished
-
\this public function closeWrite ( )
- Close write stream
-
boolean public function eof ( )
- Got EOF?
-
boolean public function write ( string $data )
- Send data to the connection. Note that it just writes to buffer that flushes at every baseloop
$data
— Data to send
-
boolean public function writeln ( string )
- Send data and appending \n to connection. Note that it just writes to buffer flushed at every baseloop
Data to send
-
\this public function onEOF ( callable $cb = NULL )
- Sets callback which will be called once when got EOF
$cb
Timer ← Libraries
namespace PHPDaemon\Core;
class Timer;
With this class can be created in the pending event (timers) time
$i = 0;
setTimeout(function($timer) use (&$i) {
D("5 seconds passed!");
if (++$i < 3) {
// start the timer for another 5 seconds
$timer->timeout();
} else {
D('Конец');
$timer->free();
}
}, 5e6);
-
integer setTimeout ( callable $cb, integer $timeout = null, integer $id = null, integer $priority = null )
- Function alias
Timer::add
$cb
— Callback$timeout
— The timeout microseconds through which the callback function to be executed$id
— timer ID$priority
— event priority timer
- Function alias
-
integer|null public $id
- Timer id
-
integer public $lastTimeout
- Current timeout holder
-
boolean public $finished = false
- Is the timer finished?
-
callable public $cb
- Callback
-
integer public $priority
- Priority
-
void public function __construct ( callable $cb, integer $timeout = null, integer|string $id = null, integer $priority = null )
- Constructor
$cb
— Callback$timeout
— Timeout$id
— Timer ID$priority
— Priority
-
void public function eventCall ( )
- Called when timer is triggered
-
void public function setPriority ( integer $priority )
- Set prioriry
$priority
— Priority
-
integer|string public static function add ( callable $cb, integer $timeout = null, integer|string $id = null, integer $priority = null )
- Adds timer
$cb
— Callback$timeout
— Timeout$id
— Timer ID$priority
— Priority
-
boolean public static function setTimeout ( integer|string $id, integer $timeout = NULL )
- Sets timeout
$id
— Timer ID$timeout
— Timeout
-
void public static function remove ( integer|string $id )
- Removes timer by ID
$id
— Timer ID
-
void public static function cancelTimeout ( integer|string $id )
- Cancels timer by ID
$id
— Timer ID
-
void public function timeout ( integer $timeout = null )
- Sets timeout
$timeout
— Timeout
-
void public function cancel ( )
- Cancels timer
-
void public function finish ( )
- Finishes timer
-
void public function __destruct ( )
- Destructor
-
void public function free ( )
- Frees the timer
TransportContext ← Libraries
namespace PHPDaemon\Core;
class TransportContext extends AppInstance;
@TODO
FS ← Libraries
namespace PHPDaemon\FS;
namespace PHPDaemon\FS;
class File;
File
-
integer public $priority = 10
- Priority
-
integer public $chunkSize = 4096
- Chunk size
-
integer public $offset = 0
- Current offset
-
string public $fdCacheKey
- Cache key
-
boolean public $append
- Append?
-
string public $path
- Path
-
boolean public $writing = false
- Writing?
-
boolean public $closed = false
- Closed?
-
void public function __construct ( resource $fd, string $path )
- File constructor
$fd
— Descriptor$path
— Path
-
resource public function getFd ( )
- Get file descriptor
-
mixed public static function convertFlags ( string $mode, boolean $text = false )
- Converts string of flags to integer or standard text representation
$mode
— Mode$text
— Text?
-
resource|boolean public function truncate ( integer $offset = 0, callable $cb = null, integer $pri = EIO_PRI_DEFAULT )
- Truncates this file
$offset
— Offset. Default is 0$cb
— Callback$pri
— Priority
-
resource|boolean public function stat ( callable $cb, integer $pri = EIO_PRI_DEFAULT )
- Stat()
$cb
— Callback$pri
— Priority
-
resource|boolean public function statRefresh ( callable $cb, integer $pri = EIO_PRI_DEFAULT )
- Stat() non-cached
$cb
— Callback$pri
— Priority
-
resource|boolean public function statvfs ( callable $cb, integer $pri = EIO_PRI_DEFAULT )
- Statvfs()
$cb
— Callback$pri
— Priority
-
resource|false public function sync ( callable $cb, integer $pri = EIO_PRI_DEFAULT )
- Sync()
$cb
— Callback$pri
— Priority
-
resource|false public function datasync ( callable $cb, integer $pri = EIO_PRI_DEFAULT )
- Datasync()
$cb
— Callback$pri
— Priority
-
resource|false public function write ( string $data, callable $cb = null, integer $offset = null, integer $pri = EIO_PRI_DEFAULT )
- Writes data to file
$data
— Data$cb
— Callback$offset
— Offset$pri
— Priority
-
resource|false public function chown ( integer $uid, integer $gid = -1, callable $cb, integer $pri = EIO_PRI_DEFAULT )
- Changes ownership of this file
$uid
— User ID$gid
— Group ID$cb
— Callback$pri
— Priority
-
resource|false public function touch ( integer $mtime, integer $atime = null, callable $cb = null, integer $pri = EIO_PRI_DEFAULT )
- touch()
$mtime
— Last modification time$atime
— Last access time$cb
— Callback$pri
— Priority
-
void public function clearStatCache ( )
- Clears cache of stat() and statvfs()
-
boolean public function read ( integer $length, integer $offset = null, callable $cb = null, integer $pri = EIO_PRI_DEFAULT )
- Reads data from file
$length
— Length$offset
— Offset$cb
— Callback$pri
— Priority
-
boolean public function sendfile ( mixed $outfd, callable $cb, callable $startCb = null, integer $offset = 0, integer $length = null, integer $pri = EIO_PRI_DEFAULT )
- sendfile()
$outfd
— File descriptor$cb
— Callback$startCb
— Start callback$offset
— Offset$length
— Length$pri
— Priority
-
resource|false public function readahead ( integer $length, integer $offset = null, callable $cb = null, integer $pri = EIO_PRI_DEFAULT )
- readahead()
$length
— Length$offset
— Offset$cb
— Callback$pri
— Priority
-
boolean public function readAll ( callable $cb, integer $pri = EIO_PRI_DEFAULT )
- Reads whole file
$cb
— Callback$pri
— Priority
-
resource|false public function readAllChunked ( callable $cb = null, callable $chunkcb = null, integer $pri = EIO_PRI_DEFAULT )
- Reads file chunk-by-chunk
$cb
— Callback$chunkcb
— Callback of chunk$pri
— Priority
-
string public function __toString ( )
- toString handler
-
void public function setChunkSize ( integer $n )
- Set chunk size
$n
— Chunk size
-
resource|false public function seek ( integer $offset, callable $cb, integer $pri = EIO_PRI_DEFAULT )
- Move pointer to arbitrary position
$offset
— Offset$cb
— Callback$pri
— Priority
-
integer public function tell ( )
- Get current pointer position
-
resource|false public function close ( )
- Close the file
-
void public function __destruct ( )
- Destructor
namespace PHPDaemon\FS;
class FileSystem;
FileSystem
Properties ← FileSystem ← FS ← Libraries
-
boolean public static $supported
- Is EIO supported?
-
\Event public static $ev
- Main FS event
-
resource public static $fd
- EIO file descriptor
-
array public static $modeTypes = [ 49152 => 's', 40960 => 'l', 32768 => 'f', 24576 => 'b', 16384 => 'd', 8192 => 'c', 4096 => 'p', ]
- Mode types
-
integer public static $badFDttl = 5
- TTL for bad descriptors in seconds
-
\PHPDaemon\Cache\CappedStorage public static $fdCache
- File descriptor cache
-
integer public static $fdCacheSize = 128
- Maximum number of open files in cache
-
string public static $eioVer = '1.2.1'
- Required EIO version
Methods ← FileSystem ← FS ← Libraries
-
void public static function init ( )
- Initialize FS driver
-
void public static function initEvent ( )
- Initialize main FS event
-
boolean public static function checkFileReadable ( string $path )
- Checks if file exists and readable
$path
— Path
-
void public static function waitAllEvents ( )
- Block until all FS events are completed
-
void public static function updateConfig ( )
- Called when config is updated
-
string public static function sanitizePath ( string $path )
- Sanitize path
$path
— Path
-
array public static function statPrepare ( mixed $stat )
- Prepare value of stat()
$stat
— Data
-
resource|true public static function stat ( string $path, callable $cb, integer $pri = EIO_PRI_DEFAULT )
- Gets stat() information
$path
— Path$cb
— Callback$pri
— Priority
-
resource|boolean public static function unlink ( string $path, callable $cb = null, integer $pri = EIO_PRI_DEFAULT )
- Unlink file
$path
— Path$cb
— Callback$pri
— Priority
-
resource|boolean public static function rename ( string $path, string $newpath, callable $cb = null, integer $pri = EIO_PRI_DEFAULT )
- Rename
$path
— Path$newpath
— New path$cb
— Callback$pri
— Priority
-
resource|false public static function statvfs ( string $path, callable $cb, integer $pri = EIO_PRI_DEFAULT )
- statvfs()
$path
— Path$cb
— Callback$pri
— Priority
-
resource|true public static function lstat ( string $path, callable $cb, integer $pri = EIO_PRI_DEFAULT )
- lstat()
$path
— Path$cb
— Callback$pri
— Priority
-
resource|true public static function realpath ( string $path, callable $cb, integer $pri = EIO_PRI_DEFAULT )
- realpath()
$path
— Path$cb
— Callback$pri
— Priority
-
resource|false public static function sync ( callable $cb = null, integer $pri = EIO_PRI_DEFAULT )
- sync()
$cb
— Callback$pri
— Priority
-
resource|false public static function syncfs ( callable $cb = null, integer $pri = EIO_PRI_DEFAULT )
- statfs()
$cb
— Callback$pri
— Priority
-
resource|boolean public static function touch ( string $path, integer $mtime, integer $atime = null, callable $cb = null, integer $pri = EIO_PRI_DEFAULT )
- touch()
$path
— Path$mtime
— Last modification time$atime
— Last access time$cb
— Callback$pri
— Priority
-
resource|boolean public static function rmdir ( string $path, callable $cb = null, integer $pri = EIO_PRI_DEFAULT )
- Removes empty directory
$path
— Path$cb
— Callback$pri
— Priority
-
resource|boolean public static function mkdir ( string $path, integer $mode, callable $cb = null, integer $pri = EIO_PRI_DEFAULT )
- Creates directory
$path
— Path$mode
— Mode (octal)$cb
— Callback$pri
— Priority
-
resource|true public static function readdir ( string $path, callable $cb = null, integer $flags, integer $pri = EIO_PRI_DEFAULT )
- Readdir()
$path
— Path$cb
— Callback$flags
— Flags$pri
— Priority
-
resource|boolean public static function truncate ( string $path, integer $offset = 0, callable $cb = null, integer $pri = EIO_PRI_DEFAULT )
- Truncate file
$path
— Path$offset
— Offset$cb
— Callback$pri
— Priority
-
true public static function sendfile ( mixed $outfd, string $path, callable $cb, callable $startCb = null, integer $offset = 0, integer $length = null, integer $pri = EIO_PRI_DEFAULT )
- sendfile()
$outfd
— File descriptor$path
— Path$cb
— Callback$startCb
— Start callback$offset
— Offset$length
— Length$pri
— Priority
-
resource|boolean public static function chown ( string $path, integer $uid, integer $gid = -1, callable $cb, integer $pri = EIO_PRI_DEFAULT )
- Changes ownership of file/directory
$path
— Path$uid
— User ID$gid
— Group ID$cb
— Callback$pri
— Priority
-
resource|true public static function readfile ( string $path, callable $cb, integer $pri = EIO_PRI_DEFAULT )
- Reads whole file
$path
— Path$cb
— Callback (Path, Contents)$pri
— Priority
-
resource public static function readfileChunked ( string $path, callable $cb, callable $chunkcb, integer $pri = EIO_PRI_DEFAULT )
- Reads file chunk-by-chunk
$path
— Path$cb
— Callback (Path, Success)$chunkcb
— Chunk callback (Path, Chunk)$pri
— Priority
-
string public static function genRndTempnam ( string $dir = null, string $prefix = 'php' )
- Returns random temporary file name
$dir
— Directory$prefix
— Prefix
-
string public static function genRndTempnamPrefix ( string $dir, string $prefix )
- Returns random temporary file name
$dir
— Directory$prefix
— Prefix
-
resource public static function tempnam ( string $dir, string $prefix, callable $cb )
- Obtain exclusive temporary file
$dir
— Directory$prefix
— Prefix$cb
— Callback (File)
-
resource public static function open ( string $path, string $flags, callable $cb, integer $mode = null, integer $pri = EIO_PRI_DEFAULT )
- Open file
$path
— Path$flags
— Flags$cb
— Callback (File)$mode
— Mode (see EIO_S_I* constants)$pri
— Priority
namespace PHPDaemon\FS;
class FileWatcher;
Implementation of the file watcher
Properties ← FileWatcher ← FS ← Libraries
-
array public $files = [ ]
- Associative array of the files being observed
-
resource public $inotify
- Resource returned by inotify_init()
-
array public $descriptors = [ ]
- of inotify descriptors
Methods ← FileWatcher ← FS ← Libraries
-
void public function __construct ( )
- Constructor
-
true public function addWatch ( string $path, mixed $cb, integer $flags = null )
- Adds your subscription on object in FS
$path
— Path$cb
— Callback$flags
— Look inotify_add_watch()
-
boolean public function rmWatch ( string $path, mixed $cb )
- Cancels your subscription on object in FS
$path
— Path$cb
— Callback
-
void public function onFileChanged ( string $path )
- Called when file $path is changed
$path
— Path
-
void public function watch ( )
- Check the file system, triggered by timer
PubSub ← Libraries
namespace PHPDaemon\PubSub;
namespace PHPDaemon\PubSub;
class PubSub;
PubSub
-
boolean public function eventExists ( string $id )
- Is event exists?
$id
— Event ID
-
boolean public function sub ( string $id, object $obj, callable $cb )
- Subcribe to event
$id
— Event ID$obj
— Subscriber$cb
— Callback
-
void public function addEvent ( string $id, \PubSubEvent $obj )
- Adds event
$id
— Event ID$obj
-
void public function removeEvent ( string $id )
- Removes event
$id
— Event ID
-
boolean public function unsub ( string $id, object $obj )
- Unsubscribe object from event
$id
— Event ID$obj
— Subscriber
-
boolean public function pub ( string $id, mixed $data )
- Publish
$id
— Event ID$data
— Data
-
boolean public function unsubFromAll ( object $obj )
- Unsubscribe object from all events
$obj
— Subscriber
namespace PHPDaemon\PubSub;
class PubSubEvent extends \SplObjectStorage;
PubSubEvent
Properties ← PubSubEvent ← PubSub ← Libraries
-
array public $sub = [ ]
- Subscriptions
-
callable public $actCb
- Activation callback
-
callable public $deactCb
- Deactivation callback
Methods ← PubSubEvent ← PubSub ← Libraries
-
void public function __construct ( )
- Constructor
-
\this public function onActivation ( callable $cb )
- Sets onActivation callback
$cb
— Callback
-
\this public function onDeactivation ( callable $cb )
- Sets onDeactivation callback
$cb
— Callback
-
object public static function init ( )
- Init
-
\this public function sub ( object $obj, callable $cb )
- Subscribe
$obj
— Subcriber object$cb
— Callback
-
\this public function unsub ( object $obj )
- Unsubscripe
$obj
— Subscriber object
-
\this public function pub ( mixed $data )
- Publish
$data
— Data
SockJS ← Libraries
namespace PHPDaemon\SockJS;
namespace PHPDaemon\SockJS;
class Session;
-
\PHPDaemon\Request\Generic public $route
-
\PHPDaemon\Structures\StackCallbacks public $onWrite
-
public $id
-
public $appInstance
-
public $addr
-
array public $buffer = [ ]
-
public $framesBuffer = [ ]
-
boolean public $finished = false
-
boolean public $flushing = false
-
integer public $timeout = 60
-
public $server
-
void public function __construct ( \Application $appInstance, string $id, array $server )
- __construct
$appInstance
— [@todo description]$id
— [@todo description]$server
— [@todo description]
-
boolean|null public function handleException ( object $e )
- Uncaught exception handler
$e
-
void public function onWakeup ( )
- Called when the request wakes up
-
void public function onSleep ( )
- Called when the request starts sleep
-
void public function onHandshake ( )
- onHandshake
-
void public function c2s ( object $redis )
- c2s
$redis
-
void public function onFrame ( string $msg, integer $type )
- onFrame
$msg
— [@todo description]$type
— [@todo description]
-
void public function poll ( object $redis )
- poll
$redis
-
void public function onWrite ( )
-
void public function finish ( )
-
void public function onFinish ( )
-
void public function flush ( )
- Flushes buffered packets
-
void public function sendPacket ( object $pct, callable $cb = null )
- sendPacket
$pct
— [@todo description]$cb
—callback ( )
— [@todo description]
-
boolean public function sendFrame ( string $data, integer $type = 0x00, callback $cb = null )
- Sends a frame
$data
— Frame's data$type
— Frame's type. See the constants$cb
— Optional. Callback called when the frame is received by client
namespace PHPDaemon\SockJS;
class Application extends \PHPDaemon\Core\AppInstance;
Options ← Application ← SockJS ← Libraries
-
redis-name (string = '')
@todo redis-name -
redis-prefix (string = 'sockjs:')
@todo redis-prefix -
wss-name (string = '')
@todo wss-name -
batch-delay (Double = '0.05')
@todo batch-delay -
heartbeat-interval (Double = '25')
@todo heartbeat-interval -
dead-session-timeout (Time = '1h')
@todo dead-session-timeout -
gc-max-response-size (Size = '128k')
@todo gc-max-response-size -
network-timeout-read (Time = '2h')
@todo network-timeout-read network-timeout-write (Time = '120s')
@todo network-timeout-write
Properties ← Application ← SockJS ← Libraries
-
public $wss
Methods ← Application ← SockJS ← Libraries
-
integer public function getLocalSubscribersCount ( string $chan )
- getLocalSubscribersCount
$chan
-
void public function subscribe ( string $chan, callable $cb, callable $opcb = null )
- subscribe
$chan
— [@todo description]$cb
—callback ( )
— [@todo description]$opcb
—callback ( )
— [@todo description]
-
void public function setnx ( string $key, mixed $value, callable $cb = null )
- setnx
$key
— [@todo description]$value
— [@todo description]$cb
—callback ( )
— [@todo description]
-
void public function setkey ( string $key, mixed $value, callable $cb = null )
- setkey
$key
— [@todo description]$value
— [@todo description]$cb
—callback ( )
— [@todo description]
-
void public function getkey ( string $key, callable $cb = null )
- getkey
$key
— [@todo description]$cb
—callback ( )
— [@todo description]
-
void public function expire ( string $key, integer $seconds, callable $cb = null )
- expire
$key
— [@todo description]$seconds
— [@todo description]$cb
—callback ( )
— [@todo description]
-
void public function unsubscribe ( string $chan, callable $cb, callable $opcb = null )
- unsubscribe
$chan
— [@todo description]$cb
—callback ( )
— [@todo description]$opcb
—callback ( )
— [@todo description]
-
void public function unsubscribeReal ( string $chan, callable $opcb = null )
- unsubscribeReal
$chan
— [@todo description]$opcb
—callback ( )
— [@todo description]
-
void public function publish ( string $chan, callable $cb, callable $opcb = null )
- publish
$chan
— [@todo description]$cb
—callback ( )
— [@todo description]$opcb
—callback ( )
— [@todo description]
-
void public function onReady ( )
- Called when the worker is ready to go
-
void public function onFinish ( )
- onFinish
-
boolean public function attachWss ( \PHPDaemon\Network\Pool $wss )
- attachWss
$wss
-
boolean public function wsHandler ( object $ws, string $path, object $client, callable $state )
- wsHandler
$ws
— [@todo description]$path
— [@todo description]$client
— [@todo description]$state
—callback ( object $route )
— [@todo description]
-
boolean public function detachWss ( object $wss )
- detachWss
$wss
— [@todo description]
-
object public function beginSession ( string $path, string $sessId, string $server )
- beginSession
$path
— [@todo description]$sessId
— [@todo description]$server
— [@todo description]
-
array public function getRouteOptions ( string $path )
- getRouteOptions
$path
— [@todo description]
-
void public function endSession ( \Session $session )
- endSession
$session
-
object public function beginRequest ( object $req, object $upstream )
- Creates Request
$req
— Request$upstream
— Upstream application instance
-
object public function callMethod ( string $method, object $req, object $upstream )
- callMethod
$method
— [@todo description]$req
— [@todo description]$upstream
— [@todo description]
namespace PHPDaemon\SockJS;
class WebSocketRouteProxy;
Methods ← WebSocketRouteProxy ← SockJS ← Libraries
-
void public function __construct ( \Application $sockjs, object $conn )
- __construct
$sockjs
$conn
-
mixed public function __call ( string $method, array $args )
- __call
$method
$args
-
void public function onFrame ( string $data, integer $type )
- Called when new frame received
$data
— Frame's contents$type
— Frame's type
-
void public function onPacket ( string $data, integer $type )
- onPacket
$data
— Frame's contents$type
— Frame's type
-
void|false public function onBeforeHandshake ( callable $cb )
- realRoute onBeforeHandshake
$cb
-
void public function onHandshake ( )
-
void public function onWrite ( )
-
void public function onFinish ( )
namespace PHPDaemon\SockJS;
class WebSocketConnectionProxy;
Methods ← WebSocketConnectionProxy ← SockJS ← Libraries
-
void public function __construct ( \Application $sockjs, object $conn )
- __construct
$sockjs
$conn
-
boolean public function __isset ( string $k )
- __isset
$k
-
mixed public function __call ( string $method, array $args )
- __call
$method
$args
-
string public function toJson ( string $p )
- toJson
$p
-
boolean public function sendFrame ( string $data, integer $type = null, callback $cb = null )
- Sends a frame
$data
— Frame's data$type
— Frame's type. See the constants$cb
— Optional. Callback called when the frame is received by client
-
boolean public function sendFrameReal ( string $data, integer $type = null, callback $cb = null )
- Sends a frame
$data
— Frame's data$type
— Frame's type. See the constants$cb
— Optional. Callback called when the frame is received by client
Application ← / TestRelay ← SockJS ← Libraries
namespace PHPDaemon\SockJS\TestRelay;
class Application extends \PHPDaemon\Core\AppInstance;
Options ← Application ← / TestRelay ← SockJS ← Libraries
wss-name (string = '')
WSS name
Methods ← Application ← / TestRelay ← SockJS ← Libraries
-
void public function onReady ( )
- Called when the worker is ready to go
Close ← Application ← / TestRelay ← SockJS ← Libraries
namespace PHPDaemon\SockJS\TestRelay;
class Close extends \PHPDaemon\WebSocket\Route;
-
void public function onHandshake ( )
- Called when the connection is handshaked
namespace PHPDaemon\SockJS\TestRelay;
class EchoFeed extends \PHPDaemon\WebSocket\Route;
-
void public function onFrame ( string $data, integer $type )
- Called when new frame received
$data
— Frame's contents$type
— Frame's type
namespace PHPDaemon\SockJS\Methods;
class JsonpSend extends \PHPDaemon\SockJS\Methods\Generic;
-
void public function run ( )
- Called when request iterated
namespace PHPDaemon\SockJS\Methods;
class Xhr extends \PHPDaemon\SockJS\Methods\Generic;
namespace PHPDaemon\SockJS\Methods;
class Generic extends \PHPDaemon\HTTPRequest\Generic;
Contains some base methods
-
void public function init ( )
- Constructor
-
void public function afterHeaders ( )
- afterHeaders
-
boolean public function outputFrame ( string $s, boolean $flush = true )
- Output some data
$s
— String to out$flush
-
void public function gcCheck ( )
- gcCheck
-
boolean public function out ( string $s, boolean $flush = true )
- Output some data
$s
— String to out$flush
-
void public function run ( )
- Called when request iterated
-
void public function w8in ( )
- w8in
-
void public function s2c ( object $redis )
- s2c
$redis
-
void public function stop ( )
- Stop
-
void public function onFinish ( )
- On finish
-
void public function internalServerError ( )
- internalServerError
namespace PHPDaemon\SockJS\Methods;
class XhrSend extends \PHPDaemon\SockJS\Methods\Generic;
-
void public function run ( )
- Called when request iterated
namespace PHPDaemon\SockJS\Methods;
class NotFound extends \PHPDaemon\SockJS\Methods\Generic;
namespace PHPDaemon\SockJS\Methods;
class Info extends \PHPDaemon\SockJS\Methods\Generic;
namespace PHPDaemon\SockJS\Methods;
class XhrStreaming extends \PHPDaemon\SockJS\Methods\Generic;
-
void public function afterHeaders ( )
- afterHeaders
namespace PHPDaemon\SockJS\Methods;
class Eventsource extends \PHPDaemon\SockJS\Methods\Generic;
-
void public function sendFrame ( string $frame )
- Send frame
$frame
-
void public function init ( )
- Constructor
namespace PHPDaemon\SockJS\Methods;
class Jsonp extends \PHPDaemon\SockJS\Methods\Generic;
namespace PHPDaemon\SockJS\Methods;
class Welcome extends \PHPDaemon\SockJS\Methods\Generic;
namespace PHPDaemon\SockJS\Methods;
class Htmlfile extends \PHPDaemon\SockJS\Methods\Generic;
-
void public function sendFrame ( string $frame )
- Send frame
$frame
-
void public function init ( )
- Constructor
namespace PHPDaemon\SockJS\Methods;
class IFrame extends \PHPDaemon\SockJS\Methods\Generic;
Applications
MongoNode ← Applications
namespace PHPDaemon\Examples;
class MongoNode;
This application provides MongoDB replication node. This makes it possible to install arbitrary hooks to add / edit / delete objects.
Requirements ← MongoNode ← Applications
Required module installed pecl / mongo and included phpdaemon / MongoCllient.
Use ← MongoNode ← Applications
MongoNode When enabled, it immediately gets the new changes in the database.
Default:
If the object has the property "_key" serialized its value is sent to the Memcache key under that name, which is set within the meaning of _key. When an object is deleted from the MongoDB, it is removed from Memcache.
If the object has the property "_ev", its value is sent to the RTEP-event under the name that is specified in the value _ev.
TelnetHoneypot ← Applications
namespace PHPDaemon\Examples;
class TelnetHoneypot;
This application provides a simple telnet server for phpDaemon.
Use ← TelnetHoneypot ← Applications
[root@gf-home-server phpdaemon.wiki]# telnet 127.0.0.1 23
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
ping
pong
ServerStatus ← Applications
namespace PHPDaemon\Applications;
class ServerStatus;
This application provides information about the state of phpDaemon over HTTP, similar to the console command phpd fullstatus
.
Use ← ServerStatus ← Applications
It is necessary to add conf/phpd.conf
:
ServerStatus {
enable 1;
}
HTTP {
enable 1;
privileged;
}
Also conf/AppResolver.php
in the method of getRequestRoute()
adding a condition to start the method beginRequest() in ServerStatus application. For example, to get information about phpDaemon at http://
/**
* Routes incoming request to related application. Method is for overloading.
* @param object Request.
* @param object AppInstance of Upstream.
* @return string Application's name.
*/
public function getRequestRoute($req, $upstream) {
if (preg_match('~^/(ServerStatus|Example)/~', $req->attrs->server['DOCUMENT_URI'], $m)) {
return $m[1];
}
}
Sample answer:
Uptime: 1 day. 11 hour. 33 min. 51 sec.
State of workers:
Total: 4
Idle: 4
Busy: 0
Shutdown: 20
Pre-init: 0
Wait-init: 0
Init: 0
Note ← ServerStatus ← Applications
If you are using --logworkersetstatus option, the line is:
- 1 - idle
- 2 - busy
- 3 - shutdown
- 4 - pre-init
- 5 - wait-init
- 6 - init
Utils
Binary ← Utils
namespace PHPDaemon\Utils;
class Binary;
This class provides a set of static methods for working with binary data.
-
string public static function labels ( string $q )
- Build structure of labels
$q
— Dot-separated labels list
-
string public static function parseLabels ( string &$data, string $orig = null )
- Parse structure of labels
&$data
— Binary data$orig
— Original packet
-
string public static function LV ( string $str, integer $len = 1, boolean $lrev = FALSE )
- Build length-value binary snippet
$str
— Data$len
— Number of bytes to encode length. Default is 1$lrev
— Reverse?
-
string public static function LVnull ( string $str )
- Build nul-terminated string, with 2-byte of length
$str
— Data
-
string public static function byte ( integer $int )
- Build byte
$int
— Byte number
-
string public static function word ( integer $int )
- Build word (2 bytes) big-endian
$int
— Integer
-
string public static function wordl ( integer $int )
- Build word (2 bytes) little-endian
$int
— Integer
-
string public static function dword ( integer $int )
- Build double word (4 bytes) big-endian
$int
— Integer
-
string public static function dwordl ( integer $int )
- Build double word (4 bytes) little endian
$int
— Integer
-
string public static function qword ( integer $int )
- Build quadro word (8 bytes) big endian
$int
— Integer
-
string public static function qwordl ( integer $int )
- Build quadro word (8 bytes) little endian
$int
— Integer
-
integer public static function getByte ( string &$p )
- Parse byte, and remove it
&$p
— Data
-
string public static function getChar ( string &$p )
- Get single-byte character
&$p
— Data
-
integer public static function getWord ( string &$p, boolean $l = false )
- Parse word (2 bytes)
&$p
— Data$l
— Little endian?
-
string public static function getStrWord ( string &$p, boolean $l = false )
- Get word (2 bytes)
&$p
— Data$l
— Little endian?
-
integer public static function getDWord ( string &$p, boolean $l = false )
- Get double word (4 bytes)
&$p
— Data$l
— Little endian?
-
integer public static function getQword ( string &$p, boolean $l = false )
- Parse quadro word (8 bytes)
&$p
— Data$l
— Little endian?
-
string public static function getStrQWord ( string &$p, boolean $l = false )
- Get quadro word (8 bytes)
&$p
— Data$l
— Little endian?
-
string public static function getString ( string &$str )
- Parse nul-terminated string
&$str
— Data
-
string public static function getLV ( string &$p, integer $l = 1, boolean $nul = false, boolean $lrev = false )
- Parse length-value structure
&$p
— Data$l
— Number of length bytes$nul
— Nul-terminated? Default is false$lrev
— Length is little endian?
-
string public static function int2bytes ( integer $len, integer $int = 0, boolean $l = false )
- Converts integer to binary string
$len
— Length$int
— Integer$l
— Optional. Little endian. Default value - false
-
string public static function flags2bitarray ( array $flags, integer $len = 4 )
- Convert array of flags into bit array
$flags
— Flags$len
— Length. Default is 4
-
string public static function i2b ( integer $len, integer $int = 0, boolean $l = false )
- Converts integer to binary string
$len
— Length$int
— Integer$l
— Optional. Little endian. Default value - false
-
integer public static function bytes2int ( string $str, boolean $l = false )
- Convert bytes into integer
$str
— Bytes$l
— Little endian? Default is false
-
integer public static function b2i ( string $str = 0, boolean $l = false )
- Convert bytes into integer
$str
— Bytes$l
— Little endian? Default is false
-
string|false public static function bitmap2bytes ( string $bitmap, integer $check_len = 0 )
- Convert bitmap into bytes
$bitmap
— Bitmap$check_len
— Check length?
-
string public static function getbitmap ( integer $byte )
- Get bitmap
$byte
— Byte
Crypt ← Utils
namespace PHPDaemon\Utils;
class Crypt;
This class contains methods related to cryptography.
-
string public static function hash ( string $str, string $salt = '', boolean $plain = false )
- Generate keccak hash for string with salt
$str
— Data$salt
— Salt$plain
— Is plain text?
-
string public static function randomString ( integer $len = null, string $chars = null, callable $cb = null, integer $pri = 0, boolean $hang = false )
- Returns string of pseudo random characters
$len
— Length of desired string$chars
— String of allowed characters$cb
— Callback$pri
— Priority of EIO operation$hang
— If true, we shall use /dev/random instead of /dev/urandom and it may cause delay
-
string public static function stringIdx ( string $str, integer $idx )
- Returns the character at index $idx in $str in constant time
$str
— String$idx
— Index
-
integer public static function randomBytes ( integer $len, callable $cb, integer $pri = 0, boolean $hang = false )
- Returns string of pseudo random bytes
$len
— Length of desired string$cb
— Callback$pri
— Priority of EIO operation$hang
— If true, we shall use /dev/random instead of /dev/urandom and it may cause delay
-
integer public static function randomInts ( integer $numInts, callable $cb, integer $pri = 0, boolean $hang = false )
- Returns array of pseudo random integers of machine-dependent size
$numInts
— Number of integers$cb
— Callback$pri
— Priority of EIO operation$hang
— If true, we shall use /dev/random instead of /dev/urandom and it may cause delay
-
integer public static function randomInts32 ( integer $numInts, callable $cb, integer $pri = 0, boolean $hang = false )
- Returns array of pseudo random 32-bit integers
$numInts
— Number of integers$cb
— Callback$pri
— Priority of EIO operation$hang
— If true, we shall use /dev/random instead of /dev/urandom and it may cause delay
-
boolean public static function compareStrings ( string $a, string $b )
- Compare strings
$a
— String 1$b
— String 2
DateTime ← Utils
namespace PHPDaemon\Utils;
class DateTime extends \DateTime;
Can pass a Unix timestamp to the constructor.
-
void public function __construct ( string $time = 'now', \DateTimeZone $timezone = null )
- Support timestamp and available date format
$time
$timezone
-
string public static function diffAsText ( integer $datetime1, integer $datetime2, boolean $absolute = false )
- Calculates a difference between two dates
$datetime1
$datetime2
$absolute
Encoding ← Utils
namespace PHPDaemon\Utils;
class Encoding;
Third-party libraries — forceutf8
-
string public static function toUTF8 ( string $text )
- Function Encoding::toUTF8
This function leaves UTF8 characters alone, while converting almost all non-UTF8 to UTF8.
It assumes that the encoding of the original string is either Windows-1252 or ISO 8859-1.
It may fail to convert characters to UTF-8 if they fall into one of these scenarios:
1) when any of these characters: ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞß
are followed by any of these: ("group B")
¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶•¸¹º»¼½¾¿
For example: %ABREPRESENT%C9%BB. «REPRESENTÉ»
The "«" (%AB) character will be converted, but the "É" followed by "»" (%C9%BB)
is also a valid unicode character, and will be left unchanged.
2) when any of these: àáâãäåæçèéêëìíîï are followed by TWO chars from group B,
3) when any of these: ðñòó are followed by THREE chars from group B $text
— Any string
- Function Encoding::toUTF8
-
string public static function toWin1252 ( string $text )
- toWin1252
$text
— Any string
-
string public static function toISO8859 ( string $text )
- toISO8859
$text
— Any string
-
string public static function toLatin1 ( string $text )
- toLatin1
$text
— Any string
-
string public static function fixUTF8 ( string $text )
- fixUTF8
$text
— Any string
-
string public static function UTF8FixWin1252Chars ( string $text )
- If you received an UTF-8 string that was converted from Windows-1252 as it was ISO8859-1
(ignoring Windows-1252 chars from 80 to 9F) use this function to fix it.
See: http://en.wikipedia.org/wiki/Windows-1252 $text
— Any string
- If you received an UTF-8 string that was converted from Windows-1252 as it was ISO8859-1
-
string public static function removeBOM ( string $str = "" )
- Remove BOM
$str
— Any string
-
string public static function normalizeEncoding ( string $str )
- Normalize encoding name
$str
— Encoding name
-
string public static function encode ( string $str )
- Encode
$str
— Any string
IRC ← Utils
namespace PHPDaemon\Utils;
class IRC;
Class used in the IRC-client and IRC-bouncer
-
array public static $codes = [ 1 => 'RPL_WELCOME', 2 => 'RPL_YOURHOST', 3 => 'RPL_CREATED', 4 => 'RPL_MYINFO', 5 => 'RPL_BOUNCE', 200 => 'RPL_TRACELINK', 201 => 'RPL_TRACECONNECTING', 202 => 'RPL_TRACEHANDSHAKE', 203 => 'RPL_TRACEUNKNOWN', 204 => 'RPL_TRACEOPERATOR', 205 => 'RPL_TRACEUSER', 206 => 'RPL_TRACESERVER', 207 => 'RPL_TRACESERVICE', 208 => 'RPL_TRACENEWTYPE', 209 => 'RPL_TRACECLASS', 210 => 'RPL_TRACERECONNECT', 211 => 'RPL_STATSLINKINFO', 212 => 'RPL_STATSCOMMANDS', 219 => 'RPL_ENDOFSTATS', 221 => 'RPL_UMODEIS', 234 => 'RPL_SERVLIST', 235 => 'RPL_SERVLISTEND', 242 => 'RPL_STATSUPTIME', 243 => 'RPL_STATSOLINE', 250 => 'RPL_STATSCONN', 251 => 'RPL_LUSERCLIENT', 252 => 'RPL_LUSEROP', 253 => 'RPL_LUSERUNKNOWN', 254 => 'RPL_LUSERCHANNELS', 255 => 'RPL_LUSERME', 256 => 'RPL_ADMINME', 257 => 'RPL_ADMINLOC1', 258 => 'RPL_ADMINLOC2', 259 => 'RPL_ADMINEMAIL', 261 => 'RPL_TRACELOG', 262 => 'RPL_TRACEEND', 263 => 'RPL_TRYAGAIN', 265 => 'RRPL_LOCALUSERS', 266 => 'RPL_GLOBALUSERS', 301 => 'RPL_AWAY', 302 => 'RPL_USERHOST', 303 => 'RPL_ISON', 305 => 'RPL_UNAWAY', 306 => 'RPL_NOWAWAY', 311 => 'RPL_WHOISUSER', 312 => 'RPL_WHOISSERVER', 313 => 'RPL_WHOISOPERATOR', 314 => 'RPL_WHOWASUSER', 315 => 'RPL_ENDOFWHO', 317 => 'RPL_WHOISIDLE', 318 => 'RPL_ENDOFWHOIS', 319 => 'RPL_WHOISCHANNELS', 321 => 'RPL_LISTSTART', 322 => 'RPL_LIST', 323 => 'RPL_LISTEND', 324 => 'RPL_CHANNELMODEIS', 325 => 'RPL_UNIQOPIS', 328 => 'RPL_CHANNEL_URL', 329 => 'RPL_CREATIONTIME', 331 => 'RPL_NOTOPIC', 332 => 'RPL_TOPIC', 333 => 'RPL_TOPIC_TS', 341 => 'RPL_INVITING', 342 => 'RPL_SUMMONING', 346 => 'RPL_INVITELIST', 347 => 'RPL_ENDOFINVITELIST', 348 => 'RPL_EXCEPTLIST', 349 => 'RPL_ENDOFEXCEPTLIST', 351 => 'RPL_VERSION', 352 => 'RPL_WHOREPLY', 353 => 'RPL_NAMREPLY', 364 => 'RPL_LINKS', 365 => 'RPL_ENDOFLINKS', 366 => 'RPL_ENDOFNAMES', 367 => 'RPL_BANLIST', 368 => 'RPL_ENDOFBANLIST', 369 => 'RPL_ENDOFWHOWAS', 371 => 'RPL_INFO', 372 => 'RPL_MOTD', 374 => 'RPL_ENDOFINFO', 375 => 'RPL_MOTDSTART', 376 => 'RPL_ENDOFMOTD', 381 => 'RPL_YOUREOPER', 382 => 'RPL_REHASHING', 383 => 'RPL_YOURESERVICE', 391 => 'RPL_TIME', 392 => 'RPL_USERSSTART', 393 => 'RPL_USERS', 394 => 'RPL_ENDOFUSERS', 395 => 'RPL_NOUSERS', 401 => 'ERR_NOSUCHNICK', 402 => 'ERR_NOSUCHSERVER', 403 => 'ERR_NOSUCHCHANNEL', 404 => 'ERR_CANNOTSENDTOCHAN', 405 => 'ERR_TOOMANYCHANNELS', 406 => 'ERR_WASNOSUCHNICK', 407 => 'ERR_TOOMANYTARGETS', 408 => 'ERR_NOSUCHSERVICE', 409 => 'ERR_NOORIGIN', 411 => 'ERR_NORECIPIENT', 412 => 'ERR_NOTEXTTOSEND', 413 => 'ERR_NOTOPLEVEL', 414 => 'ERR_WILDTOPLEVEL', 415 => 'ERR_BADMASK', 421 => 'ERR_UNKNOWNCOMMAND', 422 => 'ERR_NOMOTD', 423 => 'ERR_NOADMININFO', 424 => 'ERR_FILEERROR', 431 => 'ERR_NONICKNAMEGIVEN', 432 => 'ERR_ERRONEUSNICKNAME', 433 => 'ERR_NICKNAMEINUSE', 436 => 'ERR_NICKCOLLISION', 437 => 'ERR_UNAVAILRESOURCE', 441 => 'ERR_USERNOTINCHANNEL', 442 => 'ERR_NOTONCHANNEL', 443 => 'ERR_USERONCHANNEL', 444 => 'ERR_NOLOGIN', 445 => 'ERR_SUMMONDISABLED', 446 => 'ERR_USERSDISABLED', 451 => 'ERR_NOTREGISTERED', 461 => 'ERR_NEEDMOREPARAMS', 462 => 'ERR_ALREADYREGISTRED', 463 => 'ERR_NOPERMFORHOST', 464 => 'ERR_PASSWDMISMATCH', 465 => 'ERR_YOUREBANNEDCREEP', 466 => 'ERR_YOUWILLBEBANNED', 467 => 'ERR_KEYSET', 471 => 'ERR_CHANNELISFULL', 472 => 'ERR_UNKNOWNMODE', 473 => 'ERR_INVITEONLYCHAN', 474 => 'ERR_BANNEDFROMCHAN', 475 => 'ERR_BADCHANNELKEY', 476 => 'ERR_BADCHANMASK', 477 => 'ERR_NOCHANMODES', 478 => 'ERR_BANLISTFULL', 481 => 'ERR_NOPRIVILEGES', 482 => 'ERR_CHANOPRIVSNEEDED', 483 => 'ERR_CANTKILLSERVER', 484 => 'ERR_RESTRICTED', 485 => 'ERR_UNIQOPPRIVSNEEDED', 491 => 'ERR_NOOPERHOST', 501 => 'ERR_UMODEUNKNOWNFLAG', 502 => 'ERR_USERSDONTMATCH', ]
- IRC codes
-
array public static $codesFlip
- Flipped IRC codes
-
string public static function getCommandByCode ( integer $code )
$code
— Code
-
integer public static function getCodeByCommand ( string $cmd )
$cmd
— Command
-
array public static function parseUsermask ( string $mask )
$mask
MIME ← Utils
namespace PHPDaemon\Utils;
class MIME;
-
string public static function get ( string $path )
- Returns MIME type of the given file
$path
— Path
ShmEntity ← Utils
namespace PHPDaemon\Utils;
class ShmEntity;
Elastic heap storage in the shared memory
It used to store an array of workflow status.
-
void public function __construct ( string $path, integer $segsize, string $name, boolean $create = false )
- Constructor
$path
— Path$segsize
— Segment size$name
— Name$create
— Create
-
integer public function open ( integer $segno = 0, boolean $create = false )
- Opens segment of shared memory
$segno
— Segment number$create
— Create
-
array public function getSegments ( )
- Get open segments
-
void public function openall ( )
- Open all segments
-
boolean public function write ( string $data, integer $offset )
- Write to shared memory
$data
— Data$offset
— Offset
-
string public function read ( integer $offset, integer $length = 1 )
- Read from shared memory
$offset
— Offset$length
— Length
-
void public function delete ( )
- Deletes all segments
Terminal ← Utils
namespace PHPDaemon\Utils;
class Terminal;
This class needs work: lacks full ncurses support. If you would like to help, click on the cat!
-
void public function __construct ( )
- Constructor
-
string public function readln ( )
- Read a line from STDIN
-
void public function enableColor ( boolean $bool = true )
- Enables/disable color
$bool
— Enable?
-
void public function clearScreen ( )
- Clear the terminal with CLR
-
void public function setStyle ( string $c )
- Set text style
$c
— Style
-
void public function resetStyle ( )
- Reset style to default
-
void public function drawParam ( string $name, string $description, array $values = '' )
- Draw param (like in man)
$name
— Param name$description
— Param description$values
— Param allowed values
-
void public function drawTable ( array )
- Draw a table
Array of table's rows
Structures
ObjectStorage ← Structures
namespace PHPDaemon\Structures;
class ObjectStorage extends \SplObjectStorage;
This class provides an object store with a few additional methods
You can subclass one
Methods ← ObjectStorage ← Structures
-
integer public function each ( string $method, mixed $args )
- Call given method of all objects in storage
$method
— Method name$args
— Arguments
-
void public function removeAll ( \SplObjectStorage $obj = null )
- Remove all objects from this storage, which contained in another storage
$obj
-
object public function detachFirst ( )
- Detaches first object and returns it
-
object public function getFirst ( )
- Returns first object
PriorityQueueCallbacks ← Structures
namespace PHPDaemon\Structures;
class PriorityQueueCallbacks extends \SplPriorityQueue;
Used in Network/Client to store calls, until all available connections are busy
Methods ← PriorityQueueCallbacks ← Structures
-
void public function insert ( callable $cb, integer $pri = 0 )
- Insert callback
$cb
— Callback$pri
— Priority
-
void public function enqueue ( callable $cb, integer $pri = 0 )
- Enqueue callback
$cb
— Callback$pri
— Priority
-
callable public function dequeue ( )
- Dequeue
-
integer public function compare ( integer $pri1, integer $pri2 )
- Compare two priorities
$pri1
$pri2
-
boolean public function executeOne ( mixed $args )
- Executes one callback from the top of queue with arbitrary arguments
$args
— Arguments
-
integer public function executeAll ( mixed $args )
- Executes all callbacks from the top of queue to bottom with arbitrary arguments
$args
— Arguments
StackCallbacks ← Structures
namespace PHPDaemon\Structures;
class StackCallbacks extends \SplStack;
This class provides a stack of callback functions with several additional methods
Used in Network/Client to store the callback stack
Methods ← StackCallbacks ← Structures
-
void public function push ( callable $cb )
- Push callback to the bottom of stack
$cb
— Callback
-
void public function unshift ( callable $cb )
- Push callback to the top of stack
$cb
— Callback
-
boolean public function executeOne ( mixed $args )
- Executes one callback from the top with given arguments
$args
— Arguments
-
boolean public function executeAndKeepOne ( mixed $args )
- Executes one callback from the top with given arguments without taking it out
$args
— Arguments
-
integer public function executeAll ( mixed $args )
- Executes all callbacks with given arguments
$args
— Arguments
-
array public function toArray ( )
- Return array
-
void public function reset ( )
- Shifts all callbacks sequentially
Traits
This section describes the included traits available to developers.
ClassWatchdog ← Traits
namespace PHPDaemon\Traits;
trait ClassWatchdog;
This trait is already used in all base classes and there is no need to reuse it when inheriting from them.
This trait is needed to prevent an E_ERROR (Fatal error) level error from occurring when calling a non-existent method. E_ERROR, however, interrupts the entire workflow, which is unacceptable in the phpDaemon reality. It is strongly recommended for all classes to use.
This trait defines the following magic methods:
__call
— throws the exception UndefinedMethodCalled__callStatic
— throws the exception UndefinedMethodCalled.
StaticObjectWatchdog ← Traits
namespace PHPDaemon\Traits;
trait StaticObjectWatchdog;
This trait is already used in all base classes and there is no need to reuse it when inheriting from them.
A PHP machine can store a set of object properties in two ways: as a fixed array and as an associative hash table using the [B-tree] (http://ru.wikipedia.org/wiki/B-дерево). Initially, when creating any object, properties are stored in the form of an array with quick access. At the first attempt to set the value of a property not declared by the directive visibility $name
, the set of properties is converted to an associative table. The same happens when you delete (unset) any property). This operation in itself is not the fastest, especially with a large number of properties), but access to properties after it slows down. Of course, there are objects with intentionally dynamic set of properties, which are akin to associative arrays and they are all right. But it often happens that the programmer forgets to add a property declaration or even misprints its name. Sometimes it leads to severe performance degradation which is difficult to investigate.
Before saying that PHP is slow, it's a good idea to learn how to cook it.
This trait defines the following magic methods:
__set
— writes to the journal with the[CODE WARN]
prefix when trying to write the value of a property that does not exist or is inaccessible from this visibility area.__unset
— writes to the journal with the[CODE WARN]
prefix when trying to delete the property.
StrictStaticObjectWatchdog ← Traits
namespace PHPDaemon\Traits;
trait StrictStaticObjectWatchdog;
The behavior is similar to StaticObjectWatchdog, but this trait throws an exception instead of logging.
Defines the following magic methods:
__set
— throws a UndefinedPropertySetting exception when trying to write a value of a property that does not exist or is inaccessible from this scope.__unset
— throws a UnsettingProperty exception when trying to remove a property.
DeferredEventHandlers ← Traits
namespace PHPDaemon\Traits;
trait DeferredEventHandlers;
This trait implements a deferred events mechanism for an object.
class MyClass {
use \PHPDaemon\Traits\DeferredEventHandlers;
protected function onSomethingEvent($foo, $bar) {
return function($ev) {
list ($foo, $bar = $ev->args;
$ev->setResult("Foo is $foo, bar is $bar");
};
}
}
$o = new MyClass;
$o->onSomething(function($ev) {
D($ev->result);
// Foo is fooo, bar is barr
}, 'foo', 'barr');
$o->onSomething(function($ev) {
D($ev->result);
// Foo is fooo, bar is barr
});
При этом когда результат уже установлен, производящее его замыкание не будет вызвано повторно. Не нужно беспокоиться о повторном вызове еще до того как результат установлен, ожидающие замыкания будут вызваны правильно.
EventHandlers ← Traits
namespace PHPDaemon\Traits;
trait EventHandlers;
This trait implements a simple PUB/SUB mechanism for an object.
class MyClass {
use \PHPDaemon\Traits\EventHandlers;
}
$o = new MyClass;
$o->on('smth', function($o, $foo, $bar) {
D("Foo is $foo, bar is $bar");
});
$o->trigger('smth', 'foo', 'barr');
Do not forget that when deleting such an object, you should call the
cleanupEventHandlers()
, to avoid memory leaks.
Sessions ← Traits
namespace PHPDaemon\Traits;
trait Sessions;
This trait implements a session mechanism. The mechanism is implemented completely on its own and not as a mere wrapper around session_*
functions.
Why can't we just use the native PHP session mechanism?
- Problem #1: For long-lived processes (serving more than one client), the superglobal array
$_SESSION
will not be created anew. - Problem #2: Native implementation of sessions is blocking, which contradicts the PhpDaemon ideology of providing non-blocking I/O.
As with the native implementation, the behaviour of sessions is based on php.ini
.
The current implementation supports storing sessions in files, session.serialize_handler = php|php_binary
, lock r+!
files - milar to the native one - to prevent race condition.
You can safely use PhpDaemon with existing sessions, the serialization is compatible with native (session_encode, session_decode).
Usage examples:
$this->onSessionStart(function ($event) {
if (!$event->getResult()) {
//Session open failed
}
//Session open succeed
});
This trait is used in HTTPRequest и Servers\WebSocket\Route
DNode ← Traits
trait \PHPDaemon\WebSocket\Traits\DNode
This trait is applicable in classes inherited from Servers\WebSocket\Route
The trait implements the server portion of the protocol DNode, which is used for Remote procedure call (RPC).
Для подключение примеси нужно внести use \PHPDaemon\WebSocket\Traits\DNode
в определение своего класса-наследника Servers\WebSocket\Route.
Затем необходимо определить методы, доступные клиенту. Фактически это делает метод defineLocalMethods, который должен вызываться в onHandshake.
Давайте, для примера, создадим метод dummy
с аргументами $foo
, $bar
и $callback
:
protected function dummyMethod($foo, $bar, $callback) {
if (!static::ensureCallback($callback)) {
/* $callback не содержит функцию обратного вызова */
return;
}
$callback(md5($foo ^ $bar));
}
При обращении dummy('Hello', 'World', function(result) {...})
ответом будет вызов этой функции с аргументом bd7815679056a50c3f545b159ce5e385
— результатом выполнения md5('Hello' ^ 'World')
В качестве аргументов можно передавать передавать собственные функции обратного вызова, но учтите, что они удаляются из памяти после вызова, если возвратное значение не является true
. Таким образом, следует понимать ожидается ли повторный вызов, и в этом случае возвращать true
. Это делается во избежание утечек памяти.
Для вызова удаленного метода по имени, используйте callRemote.
Как вы могли заметить, пример
dummyMethod
использует вызовstatic::ensureCallback($callback)
. Всегда нужно проверять переданный аргумент с помощью ensureCallback перед его исполнением. В противном случае, это обернётся серьёзной брешью безопасности.
-
void public function onHandshake ( )
- Default onHandshake() method
-
\this public function callLocal ( string $method, mixed $args )
- Calls a local method
$method
— Method name$args
— Arguments
-
\this public function callRemote ( string $method, mixed $args )
- Calls a remote method
$method
— Method name$args
— Arguments
-
\this public function callRemoteArray ( string $method, array $args )
- Calls a remote method with array of arguments
$method
— Method name$args
— Arguments
-
\this public static function toJson ( mixed $m )
- Encodes value into JSON
$m
— Value
-
void public static function toJsonDebugResursive ( array &$a )
- Recursion handler for toJsonDebug()
&$a
— Data
-
void public static function toJsonDebug ( mixed $m )
- Encodes value into JSON for debugging purposes
$m
— Data
-
void public function onFinish ( )
- Called when session is finished
-
void public function cleanup ( )
- Swipes internal structures
-
mixed public function __call ( string $method, array $args )
- Magic __call method
$method
— Method name$args
— Arguments
-
void public function onPacket ( array $pct )
- Called when new packet is received
$pct
— Packet
-
void public function onFrame ( string $data, integer $type )
- Called when new frame is received
$data
— Frame's contents$type
— Frame's type
Network
Pool ← Network
namespace PHPDaemon\Network;
abstract class Pool extends ObjectStorage;
Keeps objects in the currently active compound and OtkrytyySoket.
Poole (client or server) can be instantiated from a user application, such as:
$this->httpclient = \PHPDaemon\Clients\HTTP\Pool::getInstance();
or
/* ... */
$this->pool = \PHPDaemon\Servers\FlashPolicy\Pool::getInstance([
'listen' => 'tcp://0.0.0.0:843'
]);
$this->pool->onReady();
/* ... */
But don't forget to send onReady(), onShutdown() and onConfigUpdated() events.
In most cases, the server is run by the Pool application of the same name.
# context for ssl connection (optional)
TransportContext:myContext {
tls;
certFile "/path/to/cert.pem";
pkFile "/path/to/privkey.pem";
passphrase "";
verifyPeer true;
allowSelfSigned true;
}
# listening to port 80 and 443
Pool:HTTPServer {
listen "tcp://0.0.0.0:80", "tcp://0.0.0.0:443##myContext";
port 80;
privileged;
maxconcurrency 1;
}
-
string public $connectionClass
- Default connection class
-
string public $name
- Name
-
\PHPDaemon\Config\Section public $config
- Configuration
-
integer public $maxConcurrency = 0
- Max concurrency
-
integer public $maxAllowedPacket = 0
- Max allowed packet
-
object|null public $appInstance
- Application instance object
-
void public function __construct ( array $config = [], boolean $init = true )
- Constructor
$config
— Config variables$init
-
void public function onReady ( )
- Called when the worker is ready to go
-
void public function onConfigUpdated ( )
- Called when worker is going to update configuration
-
\this public static function getInstance ( string $arg = '', boolean $spawn = true )
- Returns instance object
$arg
— name / array config / ConfigSection$spawn
— Spawn? Default is true
-
void public function setConnectionClass ( string $class )
- Sets default connection class
$class
— Connection class name
-
void public function enable ( )
- Enable socket events
-
void public function disable ( )
- Disable all events of sockets
-
boolean public function onShutdown ( boolean $graceful = false )
- Called when application instance is going to shutdown
$graceful
-
boolean public function finish ( )
- Finishes ConnectionPool
-
void public function attach ( object $conn, mixed $inf = null )
- Attach Connection
$conn
— Connection$inf
— Info
-
void public function detach ( object $conn )
- Detach Connection
$conn
— Connection
-
integer public function connect ( string $url, callback $cb, string $class = null )
- Establish a connection with remote peer
$url
— URL$cb
— Callback$class
— Optional. Connection class name
Client ← Network
namespace PHPDaemon\Network;
abstract class Client extends Pool;
@TODO
-
expose (boolean = 1)
Expose? -
servers (string|array = '127.0.0.1')
Default servers -
server (string = '127.0.0.1')
Default server maxconnperserv (integer = 32)
Maximum connections per server
-
void public function addServer ( string $url, integer $weight = NULL )
- Adds server
$url
— Server URL$weight
— Weight
-#.method ```php:p.inline.wico[data-link=https://github.com/kakserpom/phpdaemon/blob/master/PHPDaemon/Network/Client.php#L119] ( callable $cb ); ( string $url = null, callable $cb = null, integer $pri = 0 );
-.n Returns available connection from the pool -.n.ti `:hc`$url` — Address -.n `:hc`$cb` — onConnected -.n `:hc`$pri` — Optional. Priority
-
void public function detach ( object $conn )
- Detach Connection
$conn
— Connection
-
void public function markConnFree ( \ClientConnection $conn, string $url )
- Mark connection as free
$conn
— Connection$url
— URL
-
void public function markConnBusy ( \ClientConnection $conn, string $url )
- Mark connection as busy
$conn
— Connection$url
— URL
-
void public function detachConnFromUrl ( \ClientConnection $conn, string $url )
- Detaches connection from URL
$conn
— Connection$url
— URL
-
void public function touchPending ( string $url )
- Touch pending "requests for connection"
$url
— URL
-
boolean public function getConnectionByKey ( string $key, callable $cb = null )
- Returns available connection from the pool by key
$key
— Key$cb
—callback ( )
— Callback
-
boolean public function getConnectionRR ( callable $cb = null )
- Returns available connection from the pool
$cb
—callback ( )
— Callback
-
boolean public function requestByServer ( string $server, string $data, callable $onResponse = null )
- Sends a request to arbitrary server
$server
— Server$data
— Data$onResponse
—callback ( )
— Called when the request complete
-
boolean public function requestByKey ( string $key, string $data, callable $onResponse = null )
- Sends a request to server according to the key
$key
— Key$data
— Data$onResponse
—callback ( )
— Callback called when the request complete
-
boolean public function onShutdown ( boolean $graceful = false )
- Called when application instance is going to shutdown
$graceful
— Graceful?
ClientConnection ← Network
namespace PHPDaemon\Network;
class ClientConnection extends Connection;
@TODO
Methods ← ClientConnection ← Network
-
void public function __construct ( resource $fd, mixed $pool = null )
- Constructor
$fd
— File descriptor$pool
— ConnectionPool
-
boolean public function isBusy ( )
- Busy?
-
void public function onResponse ( callable $cb )
- Push callback to onReponse stack
$cb
— Callback
-
void public function onReady ( )
- Called when the connection is handshaked (at low-level), and peer is ready to recv. data
-
void public function setFree ( boolean $free = true )
- Set connection free/busy
$free
— Free?
-
void public function release ( )
- Set connection free
-
void public function checkFree ( )
- Set connection free/busy according to onResponse emptiness and ->finished
-
integer public function getQueueLength ( )
- getQueueLength
-
boolean public function isQueueEmpty ( )
- isQueueEmpty
-
void public function onFinish ( )
- Called when connection finishes
Connection ← Network
namespace PHPDaemon\Network;
abstract class Connection extends IOStream;
@TODO
Methods ← Connection ← Network
-
boolean public function isConnected ( )
- Connected?
-
void public function setDgram ( boolean $bool )
- Sets DGRAM mode
$bool
— DGRAM Mode
-
void public function setPeername ( string $host, integer $port )
- Sets peer name
$host
— Hostname$port
— Port
-
mixed public function __get ( string $name )
- Getter
$name
— Name
-
void public function getSocketName ( string &$addr, \srting &$port )
- Get socket name
&$addr
— Addr&$port
— Port
-
void public function setParentSocket ( \PHPDaemon\BoundSocket\Generic $sock )
- Sets parent socket
$sock
-
void public function onUdpPacket ( object $pct )
- Called when new UDP packet received
$pct
— Packet
-
void public function onReady ( )
- Called when the connection is handshaked (at low-level), and peer is ready to recv. data
-
void public function onInheritanceFromRequest ( \Request $req )
- Called if we inherit connection from request
$req
— Parent Request
-
void public function onFailure ( )
- Called when the connection failed to be established
-
void public function onFailureEv ( \EventBufferEvent $bev = null )
- Called when the connection failed
$bev
-
void public function __destruct ( )
- Destructor
-
boolean public function write ( string $data )
- Send data to the connection. Note that it just writes to buffer that flushes at every baseloop
$data
— Data to send
-
void public function onConnected ( callable $cb )
- Executes the given callback when/if the connection is handshaked
$cb
— Callback
-
string public function getUrl ( )
- Get URL
-
string public function getHost ( )
- Get host
-
integer public function getPort ( )
- Get port
-
boolean public function connect ( string $url, callable $cb = null )
- Connects to URL
$url
— URL$cb
— Callback
-
boolean public function connectUnix ( string $path )
- Establish UNIX socket connection
$path
— Path
-
boolean public function connectRaw ( string $host )
- Establish raw socket connection
$host
— Hostname
-
boolean public function connectUdp ( string $host, integer $port )
- Establish UDP connection
$host
— Hostname$port
— Port
-
boolean public function connectTcp ( string $host, integer $port )
- Establish TCP connection
$host
— Hostname$port
— Port
-
void public function setKeepalive ( boolean $bool )
- Set keepalive
$bool
-
void public function close ( )
- Close the connection
-
void public function setTimeouts ( integer $read, integer $write )
- Set timeouts
$read
— Read timeout in seconds$write
— Write timeout in seconds
-
void public function setOption ( integer $level, integer $optname, mixed $val )
- Set socket option
$level
— Level$optname
— Option$val
— Value
-
void public function onFinish ( )
- Called when connection finishes
IOStream ← Network
namespace PHPDaemon\Network;
abstract class IOStream;
@TODO
-
const STATE_ROOT = 0
- Alias of STATE_STANDBY
-
const STATE_STANDBY = 0
- Standby state (default state)
-
object public $pool
- Associated pool
-
void public function __construct ( resource $fd = null, object $pool = null )
- IOStream constructor
$fd
— File descriptor. Optional$pool
— Pool. Optional
-
mixed public function __get ( string $name )
- Getter
$name
— Name
-
boolean public function isFreed ( )
- Freed?
-
boolean public function isFinished ( )
- Finished?
-
\EventBufferEvent public function getBev ( )
- Get EventBufferEvent
-
resource public function getFd ( )
- Get file descriptor
-
void public function setContext ( object $ctx, integer $mode )
- Sets context mode
$ctx
— Context$mode
— Mode
-
void public function setFd ( resource $fd, object $bev = null )
- Sets fd
$fd
— File descriptor$bev
— EventBufferEvent
-
void public function setTimeout ( integer $rw )
- Set timeout
$rw
— Timeout
-
void public function setTimeouts ( integer $read, integer $write )
- Set timeouts
$read
— Read timeout in seconds$write
— Write timeout in seconds
-
void public function setPriority ( integer $p )
- Sets priority
$p
— Priority
-
void public function setWatermark ( integer|null $low = null, integer|null $high = null )
- Sets watermark
$low
— Low$high
— High
-
string|null public function readLine ( integer $eol = null )
- Reads line from buffer
$eol
— EOLS_*
-
boolean public function drain ( integer $n )
- Drains buffer
$n
— Numbers of bytes to drain
-
boolean|null public function drainIfMatch ( string $str )
- Drains buffer it matches the string
$str
— Data
-
string|false public function lookExact ( integer $n, integer $o = 0 )
- Reads exact $n bytes of buffer without draining
$n
— Number of bytes to read$o
— Offset
-
boolean public function prependInput ( string $str )
- Prepends data to input buffer
$str
— Data
-
boolean public function prependOutput ( string $str )
- Prepends data to output buffer
$str
— Data
-
string|false public function look ( integer $n, integer $o = 0 )
- Read from buffer without draining
$n
— Number of bytes to read$o
— Offset
-
string|false public function substr ( integer $o, integer $n = -1 )
- Read from buffer without draining
$o
— Offset$n
— Number of bytes to read
-
integer public function search ( string $what, integer $start = 0, integer $end = -1 )
- Searches first occurence of the string in input buffer
$what
— Needle$start
— Offset start$end
— Offset end
-
string|false public function readExact ( integer $n )
- Reads exact $n bytes from buffer
$n
— Number of bytes to read
-
integer public function getInputLength ( )
- Returns length of input buffer
-
boolean public function gracefulShutdown ( )
- Called when the worker is going to shutdown
-
boolean public function freezeInput ( boolean $at_front = false )
- Freeze input
$at_front
— At front. Default is true. If the front of a buffer is frozen, operations that drain data from the front of the buffer, or that prepend data to the buffer, will fail until it is unfrozen. If the back a buffer is frozen, operations that append data from the buffer will fail until it is unfrozen
-
boolean public function unfreezeInput ( boolean $at_front = false )
- Unfreeze input
$at_front
— At front. Default is true. If the front of a buffer is frozen, operations that drain data from the front of the buffer, or that prepend data to the buffer, will fail until it is unfrozen. If the back a buffer is frozen, operations that append data from the buffer will fail until it is unfrozen
-
boolean public function freezeOutput ( boolean $at_front = true )
- Freeze output
$at_front
— At front. Default is true. If the front of a buffer is frozen, operations that drain data from the front of the buffer, or that prepend data to the buffer, will fail until it is unfrozen. If the back a buffer is frozen, operations that append data from the buffer will fail until it is unfrozen
-
boolean public function unfreezeOutput ( boolean $at_front = true )
- Unfreeze output
$at_front
— At front. Default is true. If the front of a buffer is frozen, operations that drain data from the front of the buffer, or that prepend data to the buffer, will fail until it is unfrozen. If the back a buffer is frozen, operations that append data from the buffer will fail until it is unfrozen
-
void public function onWrite ( )
- Called when the connection is ready to accept new data
-
boolean public function write ( string $data )
- Send data to the connection. Note that it just writes to buffer that flushes at every baseloop
$data
— Data to send
-
boolean public function writeln ( string $data )
- Send data and appending \n to connection. Note that it just writes to buffer flushed at every baseloop
$data
— Data to send
-
void public function finish ( )
- Finish the session. You should not worry about buffers, they are going to be flushed properly
-
void public function close ( )
- Close the connection
-
void public function unsetFd ( )
- Unsets pointers of associated EventBufferEvent and File descriptr
-
void public function onReadEv ( object $bev )
- Called when the connection has got new data
$bev
— EventBufferEvent
-
void public function onWriteOnce ( callable $cb )
- Push callback which will be called only once, when writing is available next time
$cb
— Callback
-
void public function onWriteEv ( object $bev )
- Called when the connection is ready to accept new data
$bev
— EventBufferEvent
-
void public function onStateEv ( object $bev, integer $events )
- Called when the connection state changed
$bev
— EventBufferEvent$events
— Events
-
integer|false public function moveToBuffer ( \EventBuffer $dest, integer $n )
- Moves arbitrary number of bytes from input buffer to given buffer
$dest
— Destination nuffer$n
— Max. number of bytes to move
-
integer|false public function writeFromBuffer ( \EventBuffer $src, integer $n )
- Moves arbitrary number of bytes from given buffer to output buffer
$src
— Source buffer$n
— Max. number of bytes to move
-
string|false public function read ( integer $n )
- Read data from the connection's buffer
$n
— Max. number of bytes to read
-
string public function readUnlimited ( )
- Reads all data from the connection's buffer
Server ← Network
namespace PHPDaemon\Network;
abstract class Server extends Pool;
@TODO
-
array|null public $allowedClients
- Allowed clients
-
void public function __construct ( array $config = [], boolean $init = true )
- Constructor
$config
— Config variables$init
-
boolean public function finish ( )
- Finishes ConnectionPool
-
integer public function bindSockets ( mixed $addrs = [], integer $max = 0 )
- Bind given sockets
$addrs
— Addresses to bind$max
— Maximum
-
boolean public function bindSocket ( string $uri )
- Bind given socket
$uri
— Address to bind
-
void public function attachBound ( \PHPDaemon\BoundSocket\Generic $bound, mixed $inf = null )
- Attach Generic
$bound
— Generic$inf
— Info
-
void public function detachBound ( \PHPDaemon\BoundSocket\Generic $bound )
- Detach Generic
$bound
— Generic
-
void public function closeBound ( )
- Close each of binded sockets
-
boolean public function inheritFromRequest ( object $req, object $oldConn )
- Called when a request to HTTP-server looks like another connection
$req
— Request$oldConn
— Connection
HTTPRequest
Generic ← HTTPRequest
namespace PHPDaemon\HTTPRequest;
abstract class Generic extends \PHPDaemon\Request\Generic;
@TODO
Properties ← Generic ← HTTPRequest
-
boolean public $keepalive = false
- Keepalive?
-
integer public $responseLength = 0
- Current response length
-
array public static $hvaltr = [ '; ' => '&', ';' => '&', ' ' => '%20', ]
- Replacement pairs for processing some header values in parse_str()
-
array public static $htr = [ '-' => '_', ]
- State
Methods ← Generic ← HTTPRequest
-
void public function firstDeferredEventUsed ( )
- Called when first deferred event used
-
boolean public function sendfile ( string $path, callable $cb, integer $pri = EIO_PRI_DEFAULT )
- Output whole contents of file
$path
— Path$cb
— Callback$pri
— Priority
-
boolean public function checkIfReady ( )
- Called to check if Request is ready
-
integer public function getUploadMaxSize ( )
- Upload maximum file size
-
void public function postPrepare ( )
- Prepares the request body
-
boolean public function ensureSentHeaders ( )
- Ensure that headers are sent
-
boolean public function out ( string $s, boolean $flush = true )
- Output some data
$s
— String to out$flush
— ob_flush?
-
void public function onParsedParams ( )
- Called when request's headers parsed
-
boolean public function combinedOut ( string $s )
- Outputs data with headers (split by \r\n\r\n)
$s
— Data
-
void public function chunked ( )
- Use chunked encoding
-
void public function onWakeup ( )
- Called when the request wakes up
-
void public function onSleep ( )
- Called when the request starts sleep
-
boolean public function status ( integer $code = 200 )
- Send HTTP-status
$code
— Code
-
boolean public function headers_sent ( string &$file, integer &$line )
- Checks if headers have been sent
&$file
— File name&$line
— Line in file
-
array public function headers_list ( )
- Return current list of headers
-
boolean public function header ( string $s, boolean $replace = true, integer $code = false )
- Send the header
$s
— Header. Example: 'Location: http://php.net/'$replace
— Optional. Replace?$code
— Optional. HTTP response code
-
void public function removeHeader ( string $s )
- Removes a header
$s
— Header name. Example: 'Location'
-
integer public static function parseSize ( string $value )
- Converts human-readable representation of size to number of bytes
$value
— String of size
-
void public function onUploadFileStart ( \Input $in )
- Called when file upload started
$in
— Input buffer
-
void public function onUploadFileChunk ( \Input $in, boolean $last = false )
- Called when chunk of incoming file has arrived
$in
— Input buffer$last
— Last?
-
string public function getUploadTempDir ( )
- Returns path to directory of temporary upload files
-
boolean public function isUploadedFile ( string $path )
- Tells whether the file was uploaded via HTTP POST
$path
— The filename being checked
-
boolean public function moveUploadedFile ( string $filename, string $dest )
- Moves an uploaded file to a new location
$filename
— The filename of the uploaded file$dest
— The destination of the moved file
-
boolean public function readBodyFile ( )
- Read request body from the file given in REQUEST_BODY_FILE parameter
-
void public static function parse_str ( string $s, array &$var, boolean $header = false )
- Replacement for default parse_str(), it supoorts UCS-2 like this: %uXXXX
$s
— String to parse&$var
— Reference to the resulting array$header
— Header-style string
Input ← HTTPRequest
namespace PHPDaemon\HTTPRequest;
class Input extends \EventBuffer;
@TODO
FAQ
How to make the event, which is called after a specified time interval?
See. Library/Timer
Publications
...
Contribute
If you want to help the project, then do not hesitate to start even if you have only a bit of time for it. Any help is appreciated.
This documentation ← Contribute
We are struggling to minimize amount of undocumented parts, but we are running out of hands. Even a paragraph written in 10 minutes is a big deal.
Making changes ← This documentation ← Contribute
Consider writing in the language you know best among all others. If you are bold enough to add new language, base it upon the most similar one of existing languages.
- Fork a repository kakserpom/daemon.io
- Change Markdown (.md) files in folder
./docs/<language>/
- Compile index.html by executing
./docs/build
- Look how it looks in browser
- Send Pull Request
Want to see changes in browser without running the command? Run
watch -n1 ./docs/build
— it shall be rebuilt every second
Format of documentation ← This documentation ← Contribute
We use the Markdown with some extensions.
Nesting ← Format of documentation ← This documentation ← Contribute
For your convenience, documentation is split between many small files.
Including a file: <!-- import filepath.md -->
.
Path is relative.
Constants ← Format of documentation ← This documentation ← Contribute
Constants are used for i18n and shortcuts for frequently used templates.
They may be defined as simple as that: <!-- pvar Name Value -->
Mandatory i18n contants lang
, title
and menu-*
must be present in each translation of this documentation.
Constants may be used as templates. Calling a template: {Name Value1 Value1...}
. Values will be places in result instead of %s
.
Example of a template:
<!-- pvar tpl-outlink <a target="_blank" href="%s">%s<i class="fa fa-external-link"></i></a> -->
Example of its usage:
{tpl-outlink http://en.wikipedia.org/wiki/Markdown Markdown}
Headings ← Format of documentation ← This documentation ← Contribute
Headings may be defined like that:
## anchor # Title
## anchor # Title #> Formatted heaing
anchor
- an identifier for navigation which takes place in URL. Allowed symbols are [a-zA-Z0-9_-]
. Must be unique among anchors of its level to avoid URL collisions.
Formatted heading
is used in case if heading in the page body should differ from heading in the navigation bar.
Examples:
- Heading of first level
## contribute # Внести свою лепту
- Second level of heading:
### this-doc # This documentation
- Third level of heading:
#### markdown # Format of documentation
- Fourth level of heading:
#### headings # Headings
- Formatted heading:
### mysql # MySQL #> Clients \ MySQL
If you are adding new heading, make sure that anchor is written in English (strictly) and is simple and informative. Anchors are not supposed to be translated
Lists ← Format of documentation ← This documentation ← Contribute
You can set CSS class of list element.
-.n Element without list mark
-.n.ti Element without list mark with indentation from the previous one
The following classes are currently in use:
.n
- Элемент без символа списка.ti
- Indentation from the previous one.method
- special CSS-class for Methods
Italic and bold ← Format of documentation ← This documentation ← Contribute
Italic and bold works with *
, _
is not available due to the compatibility reasons.
Single line code ← Format of documentation ← This documentation ← Contribute
The code is wrapped into apostrophes `...`
with the additional possibility to use modifiers and CSS classes.
Modifiers are options that enable additional text processing.
Modifiers and classes are written after the opening apostrophe and must be closed with an additional one before the text starts. Modifiers are specified by a preceding :
(colon). Each modifier is indicated by one single letter. Classes are specified with a leading period.
When specifying both modifiers and classes at the same time, the modifiers must be written first.
List of modifiers:
:e
- Encode characters (default character encoding is off):p
- Parse references:h
- PHP code syntax highlighting:c
- стилевое оформление без фона и обводки
Only the class can be used at the moment, but it is better to specify the modifier
:c`.
Usage examples:
`:hc`$url`
`:p`max-requests ([Number](#config/types/number) = '10k')`
`:ph.clear`callback ( [Connection](#clients/http/connection) $conn, boolean $success )`
Multi-line code ← Format of documentation ← This documentation ← Contribute
Multi-line code with additional syntax highlighting and CSS classes. The code containing the configuration is indicated by the ruby syntax.
The only available class at the moment is `.inline' for method definitions.
Examples:
```php.inline void public post ( url $url, array $data, array $params ) void public post ( url $url, array $data, callable $resultcb ) ```
```ruby Pool:HTTPServer { listen "tcp://0.0.0.0:80", "tcp://0.0.0.0:443##myContext"; port 80; privileged; maxconcurrency 1; } ```
PHPDoc ← Contribute
Similarly, to fill in any gaps in the PHPDoc comments of the code, fork main respository, make changes and send a Pull Request.
Please note that all PHPDoc comments are written strictly in English.
Software code ← Contribute
Improvements to the program code are always welcome. If you have a module to publish and you think it deserves to be included in the main repository, send a Pull Request. Do the same with existing code improvements.
Authors of documentation
Writing ← Authors of documentation
- Dmitry Efimenko <[email protected]>
- Vasily Zorin <[email protected]>
- Alexey Sharov <[email protected]>
English proofreading ← Authors of documentation
...
Scripting ← Authors of documentation
- Dmitry Efimenko <[email protected]>
Old contributors
-
Alexey Solomin
WIKI contributions -
Dmitry "viplifes"
Clientside connector "websocket" was done by Dmitry. He also reported several important bugs. -
Dmitry "earthperson" Ponomarev
Asterisk driver -
Igor ".silent" Kalashnikov
Code formatting, some bugfixes, WIKI contributions - Sergey "sk" Kurtsev
WIKI contributions