Events info php do

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

A simple events manager function

License

kanellov/php-events

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

An single instance event manager, implemented with a simple php function. It allows you to attach and detach listeners to named events, trigger events and interrupt listeners from executing.

$ composer require kanellov/php-events 
  • Set priority to listeners for each event. When attaching a listener, you can set the priority by specifying an integer as the last argument. Listeners with greater priority value will be triggered first.
  • Collect listeners results when triggering an event. The return values from each listener are collected when triggering and returned in an array, ordered according to listeners.
  • Stop event from propagating. Events can be stopped at any time from listeners. Each listener receives a callable as the last argument, which prevents triggering the following listeners. The stopped flag is contained in the triggering results.
  • Wildcard event. You can use the wildcard event * to attach to all events. If priority is specified it will be used for this listener for any event triggered.
  • \Knlv\events(‘on’, string $event_name, callable $listener[, int $priority]); registers a $listener for event $event_name
  • \Knlv\events(‘on’, ‘*’, callable $listener[, int priority]) registers a $listener for all events

Note: All listeners receive an extra last argument. It’ s a callable that stops event propagation if called.

  • \Knlv\events(‘trigger’, string $event_name [, mixed $. ]); triggers the $event_name event and passes args to listeners.
  • \Knlv\events(‘off’); detaches all listeners
  • \Knlv\events(‘off’, $event_name) detaches all listeners for event $event_name
  • \Knlv\events(‘off’, $event_name, $listener) detaches a certain $listener for event $event_name
Читайте также:  Сумма последовательных чисел питон

Attach listeners and trigger event

\Knlv\events('on', 'event_name', function ($value) < return strtolower($value); >); \Knlv\events('on', 'event_name', function ($value) < return strtoupper($value); >); $result = \Knlv\events('trigger', 'event_name', 'TEST'); var_dump($result); /* array(2)  'stopped' => bool(false) 'results' => array(2)  [0] => string(4) "test" [1] => string(4) "TEST" > > */
\Knlv\events('on', 'event_name', function ($value) < return strtolower($value); >); \Knlv\events('on', 'event_name', function ($value) < return strtoupper($value); >, 10); $result = \Knlv\events('trigger', 'event_name', 'TEST'); var_dump($result); /* array(2)  'stopped' => bool(false) 'results' => array(2)  [0] => string(4) "TEST" [1] => string(4) "test" > > */

Stopping event propagation

\Knlv\events('on', 'event_name', function ($value, $stop) < $stop(); return strtolower($value); >); \Knlv\events('on', 'event_name', function ($value) < return strtoupper($value); >); $result = \Knlv\events('trigger', 'event_name', 'TEST'); var_dump($result); /* array(2)  'stopped' => bool(true) 'results' => array(1)  [0] => string(4) "test" > > */

The php-events is licensed under the GNU GENERAL PUBLIC LICENSE Version 3. See License File for more information.

Источник

Event Handling — PHP

Event Handling - PHP

John was assigned with user registration issue. He wanted to avoid this issue, because of complexity level that was related to this code. He was working in the project for two years and he was already fixing it for several times, however whenever he opened the code, it was like he would see it for the first time.

John was picking any other issue, delaying the registration problem to the last possible minute. He was sweating, whenever his supervisor was asking about the issue. So after several days, he decided to refactor the code, to make his work easier.

Have you ever worked on the code that was doing so much, that it was scary to change it?Or have you analyzed it from the beginning whenever you opened it?

This often comes from the code full of Sub Flows, which have been merged with the Main Flow.

Main Flow and Sub Flows

In case of the registration Main Flow would be creating an user and saving it to the database.
The Sub Flows on other hand could be:
— Sending an welcome or confirmation email
— Creating audit logs about user registration
— Synchronizing registered user to external Service

If we will look on registration (creating and saving the user) as the main flow, the sub flows happens as a result of main flow being successful.

So how do we tell that the main flow was successful?
We are doing it by Events!

Event is describing that something happened in the past. In case of the registration it would be that User Was Registered.
By subscribing to Event, we are able to run any Sub Flow.

Publishing and Subscribing to Event

Let’s start by defining Event Class.

We will publish the PersonWasRegistered event using Event Bus from PersonRegistrationService.

We can now move all the logic to Event Handlers, which subscribe to specific event.

The Event Handler subscribes to specific event based on first parameter type hint.

We have used a single class here that contains of three Event Handlers.
You are free to create separate classes for each Event Handler, if you feel the need.

You could notice, that we are injecting specific Service directly into Event Handler’s method.

This is possible due to Ecotone’s Method Invocation mechanism. You may pass any services to given Command/Event/Query Handler’s method, and Ecotone will do the work by injecting those services for you.

Happy John

John is sure now, that separating sub flows will make his code more readable, testable and solid.
He sees that changing the code for given functionality will only affect given flow now.
He can think of much easier testing as he can test Event Handlers separately and in isolation.
And is sure, that it will be easier for the team to maintain the code in the future when new sub flows will arrive.

If you want to read more about Event Handling, follow the Ecotone’s documentation.

Sign up for more like this.

Building Blocks: Exploring Aggregates, Sagas, Event Sourcing

Building Blocks: Exploring Aggregates, Sagas, Event Sourcing

Learn how building blocks enable developers to build domain-focused applications while abstracting away the complexities of integration.

Revolutionary BOA Framework: Ecotone

Revolutionary BOA Framework: Ecotone

Ecotone will change the way PHP application development is perceived thanks to enabling architecture oriented on the business.

Building Reactive Systems in PHP

Building Reactive Systems in PHP

I believe applications in 2023 and beyond should be able to self-heal, isolate failures so they don’t cascade on other components, and provide us with help to get back on track when unrecoverable error happens. They should help the developer on the design level when adding new features without

Источник

How to get Server Sent Events working nicely in PHP

20th July, 2016

Server Sent Events (SSE) (Also known as EventSource) are a great way to send data instantly to the browser, it opens a stream between the browser and the server. The browser then listens for any messages you want to relay to the browser, whether that be a visual notification to the user or just an update to existing content.

However, SSE’s can cause some issues, especially with languages like PHP that don’t cater for persistent connections by default. It can cause session locks and MySQL crashes depending on what it is you’re doing on the server-side. So, before we start, here are a few of the pitfalls that I had to overcome when I recently implemented them.

Session Locks

First and foremost, if you’re using sessions for whatever reason you will need to make them read-only on the stream. If they’re writable, this will lock them everywhere else, so any page loads will hang while the server waits for them to become writable again. This is easily fixed by calling; session_write_close();

MySQL connection limits

If you need to access a db for the streams and chances are you will want to. You will need to increase your max_connections setting for MySQL. This is because you’re keeping a MySQL connection open for every stream. So you will need to set this quite high.

Make sure headers are set correctly

You may run into issues if you don’t set the headers to be a stream on the server-side. This is easily achieved in PHP by setting the following at the start of your stream.

header("Content-Type: text/event-stream"); header("Cache-Control: no-cache"); header("Access-Control-Allow-Origin: *"); 

Run your own checks for client disconnects

I hit some issues where the connection would stay open regardless of whether the user disconnected or not. Which obviously lead to hogged server resources. I overcame this by disabling the default checks and manually checking for a disconnect.

ignore_user_abort(true); // Stops PHP from checking for user disconnect connection_aborted(); // Checks if user has disconnected or not 

OK, so now those little gotcha’s are out of the way. Here is an implementation of Server Sent Events in PHP. I used the excellent EventSource polyfill by Yaffle for browsers that don’t yet support SSE’s. First, create a file called sse.php on the server and enter the following.

 echo ":" . str_repeat(" ", 2048) . "\n"; // 2 kB padding for IE echo "retry: 2000\n"; // start stream while(true) < if(connection_aborted())< exit(); >else < // here you will want to get the latest event id you have created on the server, but for now we will increment and force an update $latestEventId = $lastEventId+1; if($lastEventId < $latestEventId)< echo "id: " . $latestEventId . "\n"; echo "data: Howdy (".$latestEventId.") \n\n"; $lastEventId = $latestEventId; ob_flush(); flush(); >else < // no new data to send echo ": heartbeat\n\n"; ob_flush(); flush(); >> // 2 second sleep then carry on sleep(2); > 

This set’s all of the appropriate settings mentioned above and does a check to see if a stream has already been established by looking at the HTTP_LAST_EVENT_ID header sent by the browser. If it has one, it is probably a brief disconnect and the stream needs to resume, otherwise it starts a new stream. We also check the query string to see if it has been passed that way from the polyfill.

We then add some padding to the initial response, which is a requirement by IE, then we start the stream with an infinite while loop. Inside we check first to see if the client has disconnected, if not we can carry on and check if we need to supply some data. Here you will need to have an event id stored against any new data that you want to supply to the browser, which should be higher than the last id that was sent. Here I am just incrementing as an example, which forces a new update everytime it checks. If no data is to be sent it just sends a heartbeat to the browser to keep the connection open.

Finally, we flush the data to the browser and sleep for 2 seconds before repeating.

On the client side we will need to establish the stream, first ensure you have implemented the polyfill and then create a stream using the code below in your javascript file.

// establish stream and log responses to the console var es = new EventSource("sse.php"); var listener = function (event) < if(typeof event.data !== 'undefined')< console.log(event.data); >>; es.addEventListener("open", listener); es.addEventListener("message", listener); es.addEventListener("error", listener); 

As a basic implementation, this is all you need. It will establish a stream and then log the response to the console. There are many uses for this API, especially with data that can change often and hopefully this has shed some light on the potential pitfalls that can occur with using SSE’s in PHP.

Источник

Оцените статью