Laravel Active version 3 released!

Laravel Active is rewritten with a absolutely new API and  released with the new major version. This document explains the new API and gives some examples about its usage.

Installation

This version is compatible with the Laravel 5 only. Require it as one of your application dependencies via Composer:

composer require hieu-le/active

Add its service provider to your providers array in the config/app.php

HieuLe\Active\ActiveServiceProvider::class,

If you want to use an alias, register that alias inside the aliases array in the config/app.php

'Active' => HieuLe\Active\Facades\Active::class,

Get the active class based on a condition

Usage:

  • Use the alias: Active::getClassIf($condition, $activeClass = 'active', $inactiveClass = '')
  • Use the application container: app('active')->getClassIf($condition, $activeClass = 'active', $inactiveClass = '')
  • Use the helper function: active_class($condition, $activeClass = 'active', $inactiveClass = '')

Explanation: if the $condition is true, the value of $activeClass is returned, otherwise the value of $inactiveClass is returned. The package comes with several methods to help you create conditions easier. You will get the class as a string as the result of these API.

active_class(true); // 'active'
active_class(false); // ''
active_class(if_uri([$currentUri]), 'selected'); // 'selected'
active_class(if_uri_pattern([$pattern1, $pattern2]), 'active', 'other'); // 'other'

Check the current URI

All of checking methods return boolean result (true or false). You can use the result in the condition of active_class or write your own expression.

Check the whole URI

Usage:

  • Use the alias: Active::checkUri(array $uris)
  • Use the application container: app('active')->checkUri(array $uris)
  • Use the helper function: if_uri(array $uris)

Explanation: you give an array of URI, the package will return true if the current URI is in your array. Remember that an URI does not begin with the slash (/) except the root.

Check the URI with some patterns

Usage:

  • Use the alias: Active::checkUriPattern(array $patterns)
  • Use the application container: app('active')->checkUriPattern(array $patterns)
  • Use the helper function: if_uri_pattern(array $patterns)

Explanation: you give an array of patterns, the package will return true if the current URI matches one of the given pattern. Asterisks may be used in the patterns to indicate wildcards.

Check the query string

Usage:

  • Use the alias: Active::checkQuery($key, $value)
  • Use the application container: app('active')->checkQuery($key, $value)
  • Use the helper function: if_query($key, $value)

Explanation: the package will return true if one of the following condition is true:

  • The current query string contains a parameter named $key with any value and the value of $value is false.
  • The current query string does not contain a parameter named $key and the value of $value is null.
  • The current query string contains a parameter named $key whose value is a string equals to $value.
  • The current query string contains a parameter named $key whose value is an array that contain the $value.
// the current query string is ?x=1&y[0]=a&y[1]=b

if_query('x', null); // true
if_query('x', 1); // true
if_query('x', 2); // false
if_query('y', 'a'); // true
if_query('y', 'c'); // false
if_query('z', null); // false

Check the current route

Check the exact route name

Usage:

  • Use the alias: Active::checkRoute(array $routes)
  • Use the application container: app('active')->checkRoute(array $routes)
  • Use the helper function: if_route(array $routes)

Explanation: you give an array of route names, the package will return true if the name of the current route (which can be null) is in your array.

Check the route name with some patterns

Usage:

  • Use the alias: Active::checkRoutePattern(array $patterns)
  • Use the application container: app('active')->checkRoutePattern(array $patterns)
  • Use the helper function: if_route_pattern(array $patterns)

Explanation: you give an array of patterns, the package will return true if the name of the current route (which can be null) matches one of the given pattern. Asterisks may be used in the patterns to indicate wildcards.

Check the route parameter value

Usage:

  • Use the alias: Active::checkRouteParam($key, $value)
  • Use the application container: app('active')->checkRouteParam($key, $value)
  • Use the helper function: if_route_param($key, $value)

Explanation: the package will return true if one of the following condition is true:

  • The current route contains a parameter named $key whose value is $value.
  • The current route does not contain a parameter named $key and the value of $value is null.

Read more about route parameter in the Laravel documentation.

Get the current values

Get the current action

Usage:

  • Use the alias: Active::getAction()
  • Use the application container: app('active')->getAction()
  • Use the helper function: current_action()

Explanation: if the current route is bound to a class method, the result will be a string like App\Http\Controllers\[email protected]. If the route is bound to a closure, the result will be the Closure string.

Get the current controller class

Usage:

  • Use the alias: Active::getController()
  • Use the application container: app('active')->getController()
  • Use the helper function: current_controller()

Explanation: if the current route is bound to a class method, the result will be the full qualified class name of the controller class, like App\Http\Controllers\YourController. If the route is bound to a closure, the result will be the Closure string.

Get the current controller method

Usage:

  • Use the alias: Active::getMethod()
  • Use the application container: app('active')->getMethod()
  • Use the helper function: current_method()

Explanation: if the current route is bound to a class method, the result will be the name of the controller method. like yourMethod. If the route is bound to a closure, the result will be the empty string.

Example

The example below illustrate the usage of this package in a sidebar with Bootstrap link group:

<div class="list-group">
    <a href="" class="list-group-item {{ active_class(if_route('users.list') && if_query('active', 1)) }}">
        Active users
    </a>
    <a href="#" class="list-group-item {{ active_class(if_route('users.list') && if_query('active', 0)) }}">
        Inactive users
    </a>
    <a href="#" class="list-group-item  {{ active_class(if_action('App\Http\Controllers\[email protected]')) }}">
        Add users
    </a>
</div>

 

 

 

Laravel (v4, v5) global site message system

The idea about global site messages

Messages here are something you want to show to users to tell them about the result of some actions. For example, after pressing the login button, a sentence appears in the new page to tell users that they have been logged in or there are any errors. In my opinion, a practical site message system should has following properties:

  • A message must belongs to one of those types: success (indicates that the previous action is done as expected), info (provides more information), warning (tells user that the action was completed, but there are something wrongs) and error (means we cannot complete the action by some reasons)
  • Each message can be generated when processing a request
  • Messages is visible in the current response or in the next one request.

When working with a project, I have created a package for Laravel (both version 4 and 5) which has all above functions: Laravel Alert (hieu-le/laravel-alert). I usually use Bootstrap alert to display site messages. So that the output of this package will follow Bootstrap alert format by default. Of course, we can change the appearance and more configurations.

Installation

You will need Composer to use this package, it is a package manager which will install dependencies of your project automatically via a json file called composer.json . There is a nice tutorial of using Composer for those who are not familiar with this awesome tool.

Add this dependency to your composer.json  file, please note that you must choose version 1.x if working with Laravel 4 and version 2.x for Laravel 5:

In a Laravel 4 project:

"hieu-le/laravel-alert": "~1.0"

In a Laravel 5 project:

"hieu-le/laravel-alert": "~2.0"

Run composer update  to make Composer install my package and its dependencies. After that, you must add the package Service Provider and register a alias to use the package easier. Open the app/config/app.php  in Laravel 4 (or config/app.php  in Laravel 5). Add the following line to the providers  array:

'HieuLe\Alert\AlertServiceProvider',

And add this line to the aliases  array

'Alert' => 'HieuLe\Alert\Facades\Alert',

Basic usage

If you want to add a message, call one of these method based on the message type:

Alert::success("Well done! You successfully read this important alert message.");
# or
Alert::info("Heads up! This alert needs your attention, but it's not super important.");
# or
Alert::warning("Warning! Better check yourself, you're not looking too good.");
# or
Alert::error("Oh snap! Change a few things up and try submitting again.");

Currently, once added, a message cannot be changed or removed. They will be displayed in group of message types, in the order of they registered. To display these message, call this method in your view template:

Alert::dump();

With those inputs, the default output will be something like this:

    <div class="alert alert-success" role="alert">
      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
      <h4><i class="icon fa fa-check"></i> Success!</h4>
      <p>Well done! You successfully read this important alert message.</p>
    </div>
    <div class="alert alert-info" role="alert">
      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
      <h4><i class="icon fa fa-info"></i> Info!</h4>
      <p>Heads up! This alert needs your attention, but it's not super important.</p>
    </div>
    <div class="alert alert-warning" role="alert">
      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
      <h4><i class="icon fa fa-warning"></i> Warning!</h4>
      <p>Warning! Better check yourself, you're not looking too good.</p>
    </div>
    <div class="alert alert-danger" role="alert">
      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
      <h4><i class="icon fa fa-ban"></i> Error!</h4>
      <p>Oh snap! Change a few things up and try submitting again.</p>
    </div>
Example of Laravel Alert message appearance
Example of Laravel Alert message appearance

Change the icons of message types

Laravel Alert comes with a set of icons for each type of message. To display these default icon, the Font Awesome must be installed in your project. You can choose another font, or use images, texts, too. Let start with copying the package config file to another location to edit.  Run one of these command from you project root folder:

Laravel 4:

php artisan config:publish hieu-le/laravel-alert

Laravel 5:

php artisan vendor:publish

A new file will be created at app/config/packages/hieu-le/laravel-alert/config  (or config/alert.php  in Laravel 5 projects). Change the content of each message type inside the icons  array to the content of your desired icons (or images, texts). For example:

return [
    'icons'       => [
        'success' => '<img src="imgs/icons/success.png" />',
        'info'    => '<img src="imgs/icons/info.png" />',
        'warning' => '<img src="imgs/icons/warning.png" />',
        'error'   => '<img src="imgs/icons/error.png" />',
    ],
]

Change the appearance of output

If you do not like the default output of messages, you can use your own view template to display them by replacing the value of view element in the package configuration file (see above section for details). The view will be rendered for each message type that contains at least one message. In your view, there will be two variables passed:

  • $icon : the string of the icon of the message type
  • $messages : the array contains all messages of the message type

Using with Laravel validation errors

For those who have worked with Laravel validation errors output, there are two ways to integrate with Laravel Alert. The first one is “copy” the validation errors and add to the global message system managed by the package manually:

if ($validator->fails())
{
    foreach($validator->messages()->all() as $message)
    {
        Alert::error($message);
    }
}

Another approach is keep your current controller code and update your view template by passing an additional argument into the Alert::dump method like this (remember that Laravel include a special variable called $errors in each view):

echo Alert::dump($errors->all());

Conclusion

With the help of the Laravel Alert package, developers now can manage and display global site messages easier and more semantically. If you need more feature or found a bug, please raise an issue in the Github repository.

Update my ‘active’ package to support Laravel 4.2

It’s about three months from my first release of hieu-le/active package. For someone does not know it, this package is created to allow developers display the active class easily based on the current route, controller, or, method of Laravel application. However, when the framework matures day by day, my package seems to be out of date. I have made some patches to make it support the current latest version of Laravel.

Change the version of dependencies

The most important thing to change is the version of Illuminate packages. As you known, Illuminate repositories is readonly and have the same version as the current laravel framework version. To make hieu-le/active works with Laravel 4.2, the version of Illuminate packages need changing from 4.1.* to 4.2.*.

Update “require” signature

From this version, you should change your composer.json to use hieu-le/active . Instead of using dev-master version, using the tilde (~) syntax as follow:

"hieu-le/active":"~1.0"

When Laravel change its mirror version, I will update my dependencies and you will not required to change your composer.json any more.

Support new method

In version 1.0, you can check the current routes by its name, controller, method, or URI. However, you need to supply the extract name to check with. The only exceptions is that you can check the URI with a patterns instead of a name. In version 1.2, I wrote new method call routePattern . With this method, now you can check the routes name with some string using the * character, eg: “*.post.create”, “*.index”, “post.*”, … This method will be very useful when working with resrouce controller.

Use “active” class for current route in Laravel 4

Updates: If you are using Laravel 5, read the documentation of the latest version instead.

When working with Laravel 4 and Bootstrap framework, I usually need determine  which menu item is currently “selected” and add the active class into that item. After installing the dwightwatson/active package and founding that that package does not fit my requirement, I decided to develop a new one and use it in my current project. You can find its source code in Github

Installation

You will need Composer to use this package in your work. Supposed that you have Composer installed in your machine, edit your project composer.json  file by adding this line into the require array:

"hieu-le/active": "~1.0"

After that, run composer update to get this package.

If you use Laravel 4, some extra steps need executing. Append these line in your providers and aliases array respectively:

# Add to `providers` array
'HieuLe\Active\ActiveServiceProvider',

# Add to `aliases` array
'Active' => 'HieuLe\Active\Facades\Active',

 Usage

Check whether current route match a pattern

# Return string 'active' if current URI is /foo
Active::pattern('foo'); 

# Return string 'selected' if current URI is /foo/bar, /foo/baz/lorem, ...
Active::pattern('foo/*', 'selected'); 

# Return string 'selected' if current URI is /foo or /bar
Active::pattern(array('foo', 'bar'), 'selected');

Check whether current route match a named route

# Return string 'active' if current route name is 'foo'
Active::route('foo');

# Return string 'selected' if current route name is 'foo' or 'bar'
Active::route(array('foo', 'bar'), 'selected')

Check whether current route match with an action formated as ‘[email protected]

# Return string 'active' if current route lead to the method 'getFoo' of the class 'FooController'
Active::action([email protected]');

# Return string 'selected' if current route lead to the method 'getFoo' of the class 'FooController' or the method 'postBar' of the class 'BarController'
Active::action(array([email protected]', [email protected]'), 'selected');

Check whether current controller is an instance of ‘FooController’ class

# Return 'active' if current controller is an instance of the 'FooController' class
Active::controller('Foo');

# Return 'selected' if current controller is an instance of 'FooController' class and current method is not 'getFoo'
Active::controller('Foo', 'selected', array('getFoo'));

Check whether current controller is an instance of ‘FooController’ class or ‘BarController’ class

# Return 'active' class if current controller is an instance of 'FooController' or 'Namespace\BarController' class
Active::controllers(array('Foo', 'Namespace\Bar'));

# Return 'selected' instead
Active::controllers(array('Foo', 'Namespace\Bar'), 'selected');

If you just want to know current controller and current method name, use these method. Notice that the “Controller” suffix will be trimmed from controller name and those prefix: “get”, “post”, “put”, “delete”, “show” will be removed from method name

# Return 'Foo' if current controller class is 'FooController'
# Return 'Namespace\Foo' if current controller class is 'Namespace\FooController'
Active::getController();

# Return 'Foo' if current method is 'getFoo' or 'postFoo'
Active::getMethod();

New method in version 1.2

Now, with my last update, you can check whether the current route name matches with one of predefined patterns by the suporting of the new method Active::routePattern Here are some examples:

# Return active for all routes that have name like "*.create"
Active::routePattern("*.create");

# Return active for all routes that have name like "*.post.index" or "*.post.edit"
Active::routePattern(['*.post.index', '*.post.edit'], "selected");

Notice that from version 1.2, this package does not support PHP 5.3 because of Laravel dependencies.

For more detail about API, your can see the class source code file

 

 

 

PHP pthreads extension for windows x64 system

Today, I have practiced with the multithread interface of PHP with the support of this POSIX pthreads extension. However, I cannot find a version for my development environment, which is built with VC++ 9.0 compiler in 64-bit system. Therefore, I have built this extension for myself and share it here for any one need it. I have tested and used this library successful in my environment.

You can download it here: https://www.mediafire.com/?r8f5t4agde8ikvd

After download this binary, extract in a new folder and copy files to your php binary folder as normal way. Remember to add extension=php_pthreads.dll to your php.ini file to load this library.

Handle mouse wheel event with jQuery jMouseWheel plugin

Recently, when answer this question on stackoverflow, I found that old way of cross-platform mouse wheel event detection have failed on new version of Firefox and Chrome. After some study on MDN, I have begun to write a new jQuery plugin to support the mouse wheel event call jMouseWheel. You can get the full source code on GitHub.

Why this plugin is created?

Well, jQuery support a event call scroll. However, it is only fired when a element have a scroll bar and the scrolling of the user make its content moved. If you want to detect just the mouse wheel event on an element, you may need another plugin like jMouseWheel.

Installation

First of all, jMouseWheel is just a plugin of jQuery and you need to include jQuery library to your HTMl first:

<script src="https://code.jquery.com/jquery-1.9.0.min.js">

Next, download the zipped file of my project and use the jMouseWheel-.min.js in your HTML:

<script src="path/to/jMouseWheel-<verion>.min.js">

Usage

Simply call the $.mousewheel(handler) in your desired element like this: 

$(document).ready(function(){
    $('#your-div').mousewheel(function(evt){
       console.log(evt.deltaY);
    });
});

For more details of the `evt` event, read the documentation from Mozilla developer network.

Current status

By the time I wrote this introduction, my plugin just allows binding to the mouse wheel event and does not support unbinding from it. I’m working to improve this plugin and make it support fully jQuery event API with on, bind and unbind method.

The new responsive design for my website

After a long time, I have finally release my first responsive layout for this website. Let’s see what is new in this version.

Responsive layout with smart phone supported

I’ve implemented three layout in this new design. One is designed for screen wider than 1280px – almost modern notebooks, one for 1024px-wide screen, the other is for smart phone screen with the minimum accepted width is 640px (Iphone 4 vertical screen width). The varying part of this design is the main menu bar, the sidebar and some module in the about page. You can resize your browser window to try with different layout.

For those who have not heard about the word responsive design, you can read wiki article as well as do some quick search in Google.

The 640px-wide version of my about page in new design
The 640px-wide version of my about page in new design
The 960px-wide version of my about page in new design
The 960px-wide version of my about page in new design
The 1280px-wide version of my about page in new design
The 1280px-wide version of my about page in new design

More semantic, more SEO friendly

In this new version, I have done a lot of things to improve the way search engines see my web pages. Now, each article will have a dedicated description and keywords for the meta tags, which is generated automatically in the previous version. I have also added Article, Review, and Person microdata into each post with the hope that Google an recognize my web pages better. For social networks, I have implemented the new View Hook module to add Open Graph meta data in to the head element of each article page as well as update the code of social sharing buttons to the latest version from the vendor.

Prepare for post thumbnail

As you can see, now each post will go along with an image (currently, my avatar). I’m developing the new gallery module to manage images, therefore, allowing attaching thumbnail for each article.

the new thumbnail position for each article
the new thumbnail position for each article

Large background

You can consider this being one of my effort to get used to with the large background designs before getting new camera by the end of this year. After getting the new camera, I’ll start learning photo and designing some themes, hope you can wait until then.

Garapi Chaos 1.2 – An Open HTML visual graph editor

Garapi

Garapi is an open visual graph editor base on HTML5, JavaScript and CSS3 technology. In the early stage, you can plot a normal function or point in to a Catersian coordinate system and export it as a image file. You can get your images easily without installing any tool except your built-in browser.

Current version: Chaos (1.2)

Features

In the current version, you can:

  • Draw the graph of normal function. Garapi supports the following mathematical functions as well as their combinations: sin(x), cos(x), tan(x), asin(x), acos(x), atan(x), abs(x), pow(x), log(x), ln(x), exp(x), sqrt(x).
  • Plot a point into the graph. You can also customize the display of its label and coordinate.
  • Moving, zooming your view port.

Release path

This is my expected release plan:

  • 1.2: basic functionalities
  • 1.3: implement setting dialog, enable saving setting and exporting function
  • 1.4: write documentations and about
  • 1.5 – 1.9: optimize code, fix bugs and improve the UI and UX.

About

The project itself is released under GNU Affero General Public License].

For further information, feel free to contact me at [email protected] or leave an issue in this project site at https://github.com/letrunghieu/Garapi.

Demo

The demo is now available at https://hieule.info/test/garapi

Wopu Blogroll WordPress plugin

Product information

Wopu Blogroll is a plugin for WordPress links. It contains two advanced blogroll widgets – widgets that display your links. Unlike using the default widget, with my plugin, you can customize your link in many ways: filtering, sorting, display in columns or scrolling. You need WordPress 2.8 or newer to run this.

Current version: 1.0.1 (Chaos). Released on Aug 08, 2011.

License: GPL version 2

Download

Wopu Links+

Wopu Link+ display your links in flexible format. With the current features, you can:

  • Select which field to be displayed (the same as the default widget)
  • Choose whether the widget title is displayed or not
  • Display your links in multi-column format (max: 5)
  • Filtering, sorting and limiting the result
  • Four arrangement algorithm to select.

Wopu Scroll Links

This widget is useful when you want to make your blogroll appear like a marquee. Using this widget, you can customize:

  • Which field to be displayed (the same as the default widget)
  • The result with filers and limitations
  • The direction, velocity and marquee type
  • The dimension of scrolling area

Installation

  • Upload plugin folder to the /wp-content/plugins/ directory.
  • Activate the plugin through the Plugins menu in WordPress.
  • Use the new two widget at the place you want.

Frequently asked questions

This section is updated based on the user’s comments here!

1. Why does the widget is not open after added in admin panel?
Answer: You can refresh your admin page or Save your widget settings to refresh it.

Acknowledgment

Thanks Max Vergelli for his jQuery Scroller plugin.

Screenshots

Wopu ScrollLink widget screenshot
Wopu ScrollLink widget screenshot
Wopu Link+ widget screenshot
Wopu Link+ widget screenshot

 

Changelog

Version 1.0.1 (Chaos)
  • Fix the compatible problem with PHP 5.2 or older