ReactPHP Tutorial #1: Event Loop And Timers

  Рет қаралды 27,396

Sergey Zhuk

Sergey Zhuk

Күн бұрын

Introduction to ReactPHP event loop and timers. Learn how to break the synchronous flow of PHP script.
=====================
Blog post: bit.ly/2Gax0Pk
Code samples: bit.ly/2LOETk0
=====================
Books:
Learning Event-Driven PHP With ReactPHP bit.ly/2Le6ath
ReactPHP For Beginners bit.ly/2kx42jW
=====================
Follow me on Twitter / zhukserega
My website sergeyzhuk.me
Become my patron: / sergeyzhuk

Пікірлер: 69
@HaraldEngels
@HaraldEngels 5 жыл бұрын
Your ReactPHP series is the best PHP related tutorial I have ever seen on KZbin. Thank you very much for taking the (huge amount of) time to share your knowledge this way :-)
@SergeyZhuk
@SergeyZhuk 5 жыл бұрын
Thank you for feedback)
@steamcode4441
@steamcode4441 2 жыл бұрын
Great tutorial, I appreciate the video!
@TornadoTwins
@TornadoTwins 4 жыл бұрын
Excellent tutorial. Thank you for taking the time to highlight areas, etc. Very very useful.
@SergeyZhuk
@SergeyZhuk 4 жыл бұрын
Thank you for feedback! 👍
@abhijeetnarvekar
@abhijeetnarvekar 5 жыл бұрын
Great! Really helped me understanding asynchronous PHP
@RodyaO_o
@RodyaO_o 3 жыл бұрын
Thank you so much. Great tutorials.
@conradho1788
@conradho1788 6 жыл бұрын
Really appreciate your work!!! Good for beginners.
@SergeyZhuk
@SergeyZhuk 6 жыл бұрын
Thank you!
@deepakbawa1367
@deepakbawa1367 4 жыл бұрын
love ypur blog as well as this youtube channel. can you please make video tutorial over reactPHP with mysql as well as mongoDB??
@AhmedMeklad
@AhmedMeklad 6 жыл бұрын
Thank you so much for this great tutorial, i have been searching for any resources about ReactPHP on KZbin, and i believe you are the first one create useful tutorial about ReactPHP. I would like to ask you about something confuse me. can we forget about node.js after using ReachPHP or i have misunderstanding?
@SergeyZhuk
@SergeyZhuk 6 жыл бұрын
Thanks! In most cases, yes. Of course, Nodejs has a huge ecosystem with npm libraries, but if you don't want to add a new language to your current stack, consider using ReactPHP. The code which is written in ReactPHP and code written in Nodejs often look very similar.
@AhmedMeklad
@AhmedMeklad 6 жыл бұрын
Thanks for advice
@ojsojs6004
@ojsojs6004 5 жыл бұрын
@@SergeyZhuk what do you think off swoole php? Do you think jit for php 8 will have good benefits for reactphp?
@SergeyZhuk
@SergeyZhuk 5 жыл бұрын
@@ojsojs6004 Haven't tried swoole yet. And definitely PHP8 will be a huge step forward for async programming.
@ojsojs6004
@ojsojs6004 5 жыл бұрын
@@SergeyZhuk at benchmark mark test, swoole php blows out node js at i/o asynchronous speed. Php 7.4(will comeout in dec 2019) will have preloading and it will even further improve the efficiency of php.
@layrochrystofer
@layrochrystofer 5 жыл бұрын
Great! Nice video. Thank you for this.
@Damian-zy9pi
@Damian-zy9pi Жыл бұрын
Hi, could you show how to create push notifications server using ReactPHP from scratch?
@CS-ep3ku
@CS-ep3ku 2 жыл бұрын
Great video Sergey! Do you know of a way to get something to happen *exactly* every second, in ReactPHP/Node/whatever? Or is the work done inside each "tick" always added to the timer interval?
@inwm07gmailcom
@inwm07gmailcom 6 жыл бұрын
Доступно все объяснили. Спасибо.
@hamdyahmed5742
@hamdyahmed5742 4 жыл бұрын
Really great efforts
@matt-stam
@matt-stam 5 жыл бұрын
Fantastic video! Thanks!
@mimpaps5913
@mimpaps5913 2 жыл бұрын
Holla! It seem like the position of the $loop->run dictates when the $loop is executed. For the same code, when I place it prior to the echo"Before timer "; then the other message prints first and irrespective of which value I pass in the timer i.e. 0 or 5 seconds. Can you please comment on that ?
@simonemenozzi1278
@simonemenozzi1278 4 жыл бұрын
which IDE are you using for the project? Thanks for the videos!
@SergeyZhuk
@SergeyZhuk 4 жыл бұрын
simone menozzi it is PHPstorm with Matherial theme
@thanasisathanasi4965
@thanasisathanasi4965 4 жыл бұрын
Thanks for your tutorials. I want to ask, is it possible to install BOTH ReactPHP/EventLoop and ReactPHP/Socket at the same project ???? Thank you friend!
@SergeyZhuk
@SergeyZhuk 4 жыл бұрын
Yes, sure.
@thanasisathanasi4965
@thanasisathanasi4965 4 жыл бұрын
@@SergeyZhuk Thank you!
@bun4uk
@bun4uk 6 жыл бұрын
Awesome! Waiting for new videos :)
@SergeyZhuk
@SergeyZhuk 6 жыл бұрын
Thanks! I'm currently working on video about promises)
@paragsatpute9397
@paragsatpute9397 4 жыл бұрын
I am using the ReactPHP event loop with periodic timer. The code works fine but the browser always shows that the activity is going on (the circle on the chrome tab is always running). Is it possible to get rid of the running circle and still the periodic loop should run. Please advise.
@Daniel83693
@Daniel83693 3 жыл бұрын
Usando o ajax amigo vc consegue escutar a requisição em segundo plano
@mimpaps5913
@mimpaps5913 2 жыл бұрын
@@Daniel83693 I guess you re saying to use ajax.
@mimpaps5913
@mimpaps5913 2 жыл бұрын
This was also a concern for me
@navjotsingh2251
@navjotsingh2251 6 жыл бұрын
You are awesome! can you do a project where you use ReactPHP, a micro-framework (like lumen), redis and vue js
@SergeyZhuk
@SergeyZhuk 6 жыл бұрын
Thank you! I'm not familiar with Vue, but I'll put it to my backlog ;)
@shmuellivshits1045
@shmuellivshits1045 5 жыл бұрын
Отличное видео. Прекрасные объяснения. Есть русскоязычная версия?
@SergeyZhuk
@SergeyZhuk 5 жыл бұрын
Спасибо! Есть субтитры на русском.
@РоманЛем
@РоманЛем 4 жыл бұрын
@@SergeyZhuk спасибо большое за урок и за субтитры отдельно!!!! :D
@stalinwesley
@stalinwesley 4 жыл бұрын
Which IDE you are using
@SergeyZhuk
@SergeyZhuk 4 жыл бұрын
It is PHPstorm with Material Theme
@antontraceur
@antontraceur 5 жыл бұрын
Очень в тему видосы ) спасибо большое! А можно где-то достать конфигурационных файл для терминала ? Хочу такую же тему себе.
@SergeyZhuk
@SergeyZhuk 5 жыл бұрын
Спасибо! Это установлен Oh My Zsh github.com/robbyrussell/oh-my-zsh с темой Agnoster https //github.com/robbyrussell/oh-my-zsh/wiki/themes#agnoster
@thanasisathanasi4965
@thanasisathanasi4965 4 жыл бұрын
Man I get an error: Uncaught TypeError: Argument 1 passed to React\EventLoop\StreamSelectLoop::cancelTimer() must implement interface React\EventLoop\TimerInterface, null given.... I use php and apache combination and I get the result on the browser. It looks nothing works until the code finishes. And instead of finishing normally it gives me the above error. Any clues?
@thanasisathanasi4965
@thanasisathanasi4965 4 жыл бұрын
A ok if I use "$loop->addPeriodicTimer(1, function (\React\EventLoop\TimerInterface $timer) use (&$counter, $loop)" instead of "$loop->addPeriodicTimer(1, function () use (&$counter, &$timer, $loop)" it works without error. But again. In a browser it waits until finish before it spits out the result ! Any clues? Thanks...
@SergeyZhuk
@SergeyZhuk 4 жыл бұрын
Hi! I think an async program in most cases is a long running script. And this it shouldn’t run in the browser. Execute your scripts in the console to see the results.
@thanasisathanasi4965
@thanasisathanasi4965 4 жыл бұрын
@@SergeyZhuk Thank you brother. I was trying to research on the issue and somebody from the reactphp chat room ( gitter.im/reactphp/reactphp ) suggested the following: "By definition you can't run a "simple socket connection" and view it in the browser. The browser talks HTTP or Websocket (which are protocols on top of TCP sockets) and the socket is a raw socket (in most cases TCP or UDP), so you need either a HTTP server (see react/http) or a Websocket server (which uses HTTP as handshake, see RatchetPHP for a high level server)."
@AlexSmolyankin
@AlexSmolyankin 6 жыл бұрын
How do you get such nice arrows for calling methods from objects?
@SergeyZhuk
@SergeyZhuk 6 жыл бұрын
Try this: Settings -> Editor -> Font -> Enable font ligatures
@AlexSmolyankin
@AlexSmolyankin 6 жыл бұрын
Пасиб)
@sunil.b
@sunil.b 6 жыл бұрын
github.com/tonsky/FiraCode SublimeText (3146+) Other editors mentioned in a repos
@DevelopWithDan
@DevelopWithDan 6 жыл бұрын
I love your videos, but it would be really helpful if you would put your code for this series in its own github repo or paste a pastebin link in each one. Your github is different from this and so is your blog. I'm getting errors and have to constantly pause the video.
@SergeyZhuk
@SergeyZhuk 6 жыл бұрын
Yes, sure! I'll add a github repo and a link to it.
@DevelopWithDan
@DevelopWithDan 6 жыл бұрын
Thank you! I'm having an issue getting a few of these things to work as in the video and I'm having a hard time figuring out if it is the fact that I'm on windows or if there is an error in my code. You type fast! Thanks so much for your help!
@SergeyZhuk
@SergeyZhuk 6 жыл бұрын
Here is the link to code samples - bit.ly/2LOETk0. I've also added it to the description.
@layrochrystofer
@layrochrystofer 5 жыл бұрын
Hey Sergey, How could I test php react?
@SergeyZhuk
@SergeyZhuk 5 жыл бұрын
Hi! I think that you can test values being passed between different components. So, you have to deal with promises and check whether they resolve with expected values or fail. I have written a library for it github.com/seregazhuk/php-react-promise-testing Maybe it will help you :)
@antontraceur
@antontraceur 5 жыл бұрын
Как на счёт использования такой методики для симулирования крона ?
@SergeyZhuk
@SergeyZhuk 5 жыл бұрын
Вполне норм. Даже либа уже есть под это дело github.com/WyriHaximus/reactphp-cron
@antontraceur
@antontraceur 5 жыл бұрын
@@SergeyZhuk в итоге я запустил крон на серваке, который качает с БД инфу по которой запускаються таски с помощью ReactPHP Timer. Спасибо за ответ!
@MrTiomanisland
@MrTiomanisland 5 жыл бұрын
What editor is this? Tnx
@SergeyZhuk
@SergeyZhuk 5 жыл бұрын
It is PHPStorm with Material Theme.
@murat.kosshi-hz9ii
@murat.kosshi-hz9ii 11 ай бұрын
good good do you from Russian????
@maisei88
@maisei88 5 жыл бұрын
Я все понимаю фрэйворки модные фишки, но БЛИН. Зачем так извращаться с PHP если есть CRON и другие инструменты которые дают возможность обойтись без КОСТЫЛЕЙ. Если вам не хватает знания языка и умений его применять: ПРИКЛАДЫВАЙТЕ ПОДОРОЖНИК К ЭРАНУ! PS: Извиняюсь грубо, и выгляжу как хэйтер, но ребята такие "расширения" лично мне не понятны и тому кто после вас будет работать с этим кодом, тоже будет очень и очень весело. PS:PS: Никаких притензий к автору курса и его изложению. все касается только этого костыля!!!!!!
@SergeyZhuk
@SergeyZhuk 5 жыл бұрын
Спасибо за комментарий. Всё так, просто не всегда в проекте есть возможность поюзать другой язык и расширить свой стэк. Например надо где-то асинхронно собрать данные из нескольких источников или запилить long-running процесс. Вот тут ReactPHP может помочь. Цель видосов - показать, что в PHP можно довольно просто реализовать асинхронность и синтаксически она будет очень похожа на nodejs.
@maisei88
@maisei88 5 жыл бұрын
@@SergeyZhuk Срегей, я вас понимаю, но сервер должен оставаться сервером, PHP это не тот случай когда есть такая жесткая необходимость в многопоточности или подобных таймерах(для этого вы будете удерживать запущенные PHP процессы, что НЕ ЕСТЬ ХОРОШО) - К примеру собрать данные из нескольких источников в пределах жизни одно PHP процесса, вообще не проблема, процесс умер - ресурсы освободились!!! - long-running процесс - это я как раз понимаю для таймеров использовать, но зачем когда есть CRON. и MySql schedules. Можете написать что для windows нет крона, но есть docker и вагрант. И на моей памяти на windows серверах очень большие проэкты ОЧЕНЬ ОЧЕНЬ редко поднимались. ЗЫ: Спасибо за то что делаете курсы более доступными, к вам нет никаких претензий. Есть только вопросы к тем кто все это сделал и тем кто это использует. (на мой личный взгляд это недостаток квалификации)
@SergeyZhuk
@SergeyZhuk 5 жыл бұрын
@@maisei88 Возможно этот конекретный скринкаст выглядит дико из-за того, что в нём описаны слишком low-level детали. В реальном же асинхронном приложении врятли придётся напрямую общаться с циклом событий и таймерами. На канале есть плейлист, в котором я описываю создание реального асинхронного приложения на PHP - парсера картинок. Может быть скринкасты из него помогут взглянуть на синхронный PHP под другим углом ;)
@mikhail-polyarus
@mikhail-polyarus Жыл бұрын
можно было бы и на русском, если такое произношение..
@adskfksefn
@adskfksefn 2 жыл бұрын
а есть на русском?
ReactPHP Tutorial #2: Streams
7:09
Sergey Zhuk
Рет қаралды 11 М.
ReactPHP Tutorial #4: Simple Chat With Sockets - Server
11:26
Sergey Zhuk
Рет қаралды 16 М.
Epic Reflex Game vs MrBeast Crew 🙈😱
00:32
Celine Dept
Рет қаралды 39 МЛН
Миллионер | 1 - серия
34:31
Million Show
Рет қаралды 2,7 МЛН
Seja Gentil com os Pequenos Animais 😿
00:20
Los Wagners
Рет қаралды 18 МЛН
She's very CREATIVE💡💦 #camping #survival #bushcraft #outdoors #lifehack
00:26
React и PHP интегрируем бекенд и фронтенд
25:11
WebDev с нуля. Канал Алекса Лущенко
Рет қаралды 31 М.
Aсинхронный PHP / Антон Шабовта (Onliner)
51:29
Pushing the Limits of PHP with ReactPHP - Christian Lück
49:50
Scotland PHP
Рет қаралды 2 М.
Introduction to ReactPHP and asynchronous PHP
14:36
Sergey Zhuk
Рет қаралды 11 М.
Hacking ARP with Python and Kali Linux (and capture passwords)
20:03
Epic Reflex Game vs MrBeast Crew 🙈😱
00:32
Celine Dept
Рет қаралды 39 МЛН