ReactPHP and Symfony

I started listening to a great Podcast series which talks a lot about different PHP and server technologies. Where on one of the later episodes, they talk about ReactPHP.

ReactPHP is a great asynchronous solution for PHP. It offers non-blocking async, which is fantastic and can be easily compared to NodeJS (although we won’t be doing that here).

I have now started exploring the technology, and what it is capable of, one of my great project ideas is to have it listen on Twitter’s Streaming API and post coordinates of a certain search query. As it picks up new posts, it will cache them on a database server for historical reasons. This would be a great way to visualise certain stories or World events as they happen.

To start this project off, I decided to not only use ReactPHP but also to merge it in with the Symfony framework. This means I can use ReactPHP within an MVC framework and have my code better organised.

A quick Google pointed me to this article Super Speed Symfony. I followed his quick tutorial on getting these working alongside one another. He had a mistake in his code which I quickly fixed, and now I was ready to get to work.

The barebones framework can be found on my Github for your personal use and exploration here as the original poster had not thought of doing this himself. I thought I would take the lead so others can use it and help in the future.

If you clone my repo, you will be able to run in the project root…

php web/app.php

This will start up a web server running ReactPHP on the web address 127.0.0.1:1337. You can see this code within app/AppKernal.php. It converts React’s requests into a Symfony request so you can carry on using Symfony as needed. You should then be able to constantly listen in on requests and create some pretty nice async apps.


Some of you may be wondering why I didn’t try going down the Laravel route as I’m a huge fan of that framework. However, I felt like it wouldn’t fit in with how Laravel deals with HTTP requests. Also, it would be a lot more straight forward to implement with Symfony and their HTTP requests instead. However, I could be wrong and would love for someone to prove it if I am.


This is it for my post on this subject for now. However, when I have a more solid app, I will be posting it here along with any tutorials to help others out. I hope this has helped others and I would love it if you shared your ReactPHP projects.

Subscribe to my weekly newsletter!

If you’d like a weekly email in your inbox, please join the newsletter by entering your email address below.

Subscription received!

Please check your email to confirm your newsletter subscription.

By subscribing, you agree with Revue’s Terms and Privacy Policy.

Laravel 4: How To Use Jquery UI Sortable

Laravel 4: How To Use Jquery UI Sortable

Click and drag sorting

I needed a way to change the sort order of my data inside of an admin interface which I have created. After a little looking around, I found many tutorials which would show how to get this done with JQuery. But wouldn’t show the best way to handle this data (and in my case using Laravel to handle this data). I dug around for quite a bit, but I ended up finding this lovely little tutorial by dragonfire1119 which was called How To Use Jquery UI Sortable In Laravel 4.

The only trouble is, when you follow this tutorial, it could be tidied up a little, here is my version…

// Place this inside your View

@foreach($categories as $category)
    sort me
@endforeach

Here is the JQuery…

$(document).ready(function () {
    $('.sortable').sortable({ cursor: 'move', axis: 'y', update: function () {
        var order = $(this).sortable('toArray');
        $.post('{{ URL::route('Sliders::sort') }}', { order: order })
    }
    });
});

And then your Controller will look like this…

<?php
public function sort() {
    $input = Input::get('order');
    $i = 1;
    
    foreach($input as $value) {
        $banner = Banner::find($value);
    
        $banner->sort_by = $i;
        $banner->save();
        
        $i++;
    }
}

The JQuery and Controller could also look like this…

$(document).ready(function () {
    $('.sortable').sortable({ cursor: 'move', action (event, ui) {
        var data = $(this).sortable('serialize');
        
        $.ajax({ data: data, type: 'POST', url: '{{ URL::route('Sliders::sort') }}' });
    }
    });
});

Updated Controller…

<?php
public function sort() {
    $input = Input::get('item');
    $i = 0;
    foreach($input as $value) { $banner = Banner::find($value);
        $banner->sort_by = $i;
        $banner->save();
        $i++;
    }
}

I think that both work just as well and it is down to personal preference. If you would like to know where I got the second method from, you can take a look here.

As always, if you have any comments/suggestion the please feel free to let me know in the comments.

Laravel AJAX Tutorial Using HTML5’s FormData

Laravel AJAX Tutorial Using HTML5’s FormData

For this tutorial, I will show you guys how I managed to create an image uploader for your profile image. This is very similar to how Facebook’s/Twitter’s functionality.

Routes

First of all, let’s create the routes, for this, we will need to create a get and post route…

<?php
Route::get('{username}', 'UsernameController@show');
Route::post('{username}/upload', 'UploadController@profileImage');

Controllers

Remember that you can name the controllers and methods anything you like, as long as you keep everything consistent. Now we need to create the controllers and methods which are as follows…

<?php
// User Controller, index mehod
public function show($username) {
    $user = User::where('username', $username)->first(); $userData = User::find($user->id)->UserDetail;

    return View::make('user', array( 'userData'=> $userData ))->with('user', $user);
}

We are trying to get the user’s information where it matches in the URI. As you can see, I have a one to one relationship with a user and a user’s information (called UserDetail). I believe the user array could be placed along with the user data array. However, I decided to place this inside the with a method.

Now we need to handle the image data which will upload the image to the background. Without anyone knowing it’s happening…

<?php
// UploadController, profileImage method
public function profileImage($username){
    $user = User::where('username', $username)->first();

    $temp = $_FILES['upload']['tmp_name']; $image = $_FILES['upload']['name'];
    $ext = pathinfo($image, PATHINFO_EXTENSION);
    
    $newFilename = uniqid($user->id);
    
    if(!is_dir("images/$username/")) { mkdir("images/$username", 0777); }
    
    $img = Image::make($temp);
    
    $img->fit(130, 130);
    
    $src = "images/$username/$newFilename.$ext";
    
    $img->save($src);
    
    $query = User::find($user->id)->profileImage; $query->src = $src;
    $query->alt = $username . '\'s Profile Image';
    $query->save();
}

Firstly, we need to match the username with the username in the URI, after this, we grab the image and process it. Please note that I am using the Intervention/Image package, which you can easily grab and install to implement it on your website. We check to see if the directory exists, if it doesn’t, then we create it with r/w permissions. I then use the image package to create an image which is 130px X 130px, the fit method will automatically crop the image so it doesn’t look stretched and horrible. We then give it a source which tells it where to save this image which then gets saved. Afterwards, we call the database and find the user to set the image src and alt rows.

Blade templates

Now that we have all the backend magic happening, we actually need to create a view which displays the form and automatically refreshes the image upon upload completion…

@extends('layout')

@section('content')

    <div class="row">
    
        <div id="profile-wrapper">
        
            <div class="large-2 columns pull-left">
                <img class="profile-thumb th" src="/{{ $user->profileImage->src }}"
                    alt="Profile Image" />
            </div>
            
            <h2>About</h2>
            
            @if(isset($loggedIn) && $loggedIn->username == $user->username)
                <a href="#" class="upload-link"> Upload a file </a>
                <div class="hidden-upload">
                    {{ Form::open(array(
                        'action' => array('User::upload',
                        $user->username),
                        'files' => 'true',
                        'id' => 'image-form')) }}
                        {{ Form::file('upload', array('class' => 'profile-upload')) }}
                    {{ Form::close() }}
                </div>
            @endif
        </div>
    
        {{ $userData->about }}
    </div>

@stop

Javascript (Ajax)

We only want to show this hidden form if the user is logged in and it’s the same logged in user which is seeing their own profile. As you can see, we are using Laravel’s blade syntax which makes this page look a lot cleaner and easier to see what is going on. Right, now we need the JQuery which will send the image to the post controller we recently created…

<script>
    if(isset(user)) {
        form.change(function() {
            var formData = new FormData($('form')[0]);
            
            jQuery.ajax({
                url: '{{ $user->username }}/upload'
                data: formData,
                processData: false,
                contentType: false,
                type: 'post',
                success: function(
                    window.location.reload(true);
                )
            })
        })
    }
</script>

I have created my own scripts.blade.php which gets placed into my layout.blade.PHP, you can do the same, or you can include this within the page itself. I then added an if statement to avoid any errors for when a user isn’t logged in. For our JQuery creates a new format function and passes in the form we created, we then call the ajax method and pass it some parameters.

  • URL: sets the URL to where the image needs to get passed to, this is the route we created above.
  • data: sets the data to formData.
  • processData and contentType are both set to false, this has to be set to avoid any future errors.
  • type: We set this to post as it is a post method.
  • success: On success, it will refresh the window to display the newly uploaded image.

Styles

There you guys have it, this is all we need to create our really awesome AJAX upload form. However, you guys might be wondering, how do we hide the form? We here are the optional steps so you can create a hidden form which gets shown upon mouse hover…

.upload-link {
    position: absolute;
    top: 100px;
    left: 35px;
    z-index: 0;
}

#profile-wrapper:hover .upload-link {
    display: inline; background: rgba(0, 0, 0, 0.8);
    color: #fff;
    padding: 2px;
}

.hidden-upload {
    position: absolute;
    top: 100px;
    left: 35px;
    z-index: 1;
}

.hidden-upload .profile-upload {
    opacity: 0;
}

Now, that is all there is (I promise). If you have any questions, comments or feedback, then please feel free to drop a comment down below. I always like to read what you guys have to say and love replying back to you. I hope you look forward to my next Blog post.

Laravel user Registration and Login

Using Laravel packages to help us

This will be a fairly simple tutorial as I’m not re-creating the wheel here. I started by developing a login/registration system by myself until I start talking to people in Laravel’s IRC. There is a package which did everything I needed it to do which was as follows…

  • Register a user with the following credentials; Username, Email, Password and of course Confirm Password.
  • The user then gets sent an email to confirm registration.
  • The user confirms registration and can now use the website by logging in.
  • The link in case the user forgets the password, which then creates a link to confirm so the user can then change his/her password.
  • Remember me functionality.
  • Logging out
  • Completely customisable in terms of layout and functionality.

Some people had spoken about a Laravel package which does all of this called Zicaco/confide. This package is absolutely brilliant and does everything I could ask for whilst still maintaining the simplicity of migrating it into something you have already developed.

We need to start off by installing this package, place “zizaco/confide”: “~4.0@dev” into your Composer’s require key. You then place ZizacoConfideServiceProvider’, inside Laravel’s provider’s array. Finally, add this into Laravel’s aliases array ‘Confide’ => ‘ZizacoConfideFacade’, .

(PLEASE NOTE: I am currently using version 3.2.* of this package and I currently haven’t upgraded. I am sure that the experience will be similar, but if you have any queries then feel free to email me).

Once you have installed your package successfully, you can run these commands to get everything up and running… php artisan confide:controllerphp artisan confide:routescomposer dump-autoload. And as the docs say, you are good to go.

You can test it out by going to localhost/users/create to see what it has made for you. Of course, you can go on and change the layout, the control and anything else which you find you need to change.

If you need any help, then please let me know and I will try to help you out. I will also be trying to upgrade to the latest version and will release a step by step guide on how to do this.

First Laravel Tutorial – Controllers and Routes

Commence quick and helpful tutorial…

Previously on a Laravel project, I had to have a slug within my routes which would point to two different tables within my database. I needed a controller which would do the thinking for me. And by this I mean, in my routes I would have…

Route::get('{slug}', 'URLController@index');

And in my Controller, I would have the following to do the thinking for me…

public function index($slug)
{
    if(Page::where('slug', $slug)) {
        //Show page property
    }
    else if(Blog::where('slug', $slug)) {
        //Show Blog property
    }
}

So here we have our logic saying if there is anything in the page table where the slug matches. We show the page with that slug otherwise, show a blog post with the matching slug.

This might not be the best example as a lot of people would have a blog post going to ‘blog/{slug}’ and you might even have the page go to ‘page/{slug}’, but the page structure of a site is always changing and it depends on how you feel people should view your site.

I have found one problem with this mind, if nothing gets found then it will just show a blank page, I haven’t found the good logic which will display errors. Or if you are in production a 404 page.