2015年11月27日 星期五

The reason why singleton is a “problem” with PHPUnit

So we add to our test:
1
2
3
4
5
6
7
8
class FooTest extends PHPUnit_Framework_TestCase
{
...
    public function tearDown()
    {
        Foo::tearDown();
    }
}
And now we implement the tearDown function in our Foo Class

1
2
3
4
public static function tearDown()
{
    static::$instance = NULL;
}

refer : http://gonzalo123.com/2012/09/24/the-reason-why-singleton-is-a-problem-with-phpunit/

2015年11月24日 星期二

Debug Your App with the Laravel Debugbar

Debug Your App with the Laravel Debugbar

The Laravel Debugbar by Barry vd. Heuvel is a package that allows you to quickly and easily keep tabs on your application during development. With a simple installation and powerful features, theDebugbar package is one of the cornerstone packages for Laravel.
The debugbar is already updated for Laravel 5 and I wanted to show you all the great features it includes.

Installing the Laravel Debugbar

Installation is extremely simple. I was about to have it running in under five minutes, and four of those was waiting on composer. Here are the steps to get it setup and going.
In your Laravel 5 project require the package:
composer require barryvdh/laravel-debugbar
Next open config/app.php and inside the ‘providers’ array add:
'Barryvdh\Debugbar\ServiceProvider',
Finally, if you wish to add the facades add this to the ‘aliases’ array:
'Debugbar' => 'Barryvdh\Debugbar\Facade',
Now as long as your app is in debug mode the bar will already be loading showing some nice stats about the page you are viewing.

Getting to know debugbar

You have the user interface of the debugbar mastered in a few short minutes and it’s really powerful. Let’s look at all the default settings that are included:
Messages
debugbar-messages
Messages is a special section, it’s only loaded by calling the facade from within your code.
Debugbar::info($object);
Debugbar::error('Error!');
Debugbar::warning('Watch out…');
Debugbar::addMessage('Another message', 'mylabel');
The messages include the PSR-3 levels (debug, info, notice, warning, error, critical, alert, emergency)
Timeline
debugbar-timeline
The timeline is perfect for fixing the bottlenecks in your code. Here are a few examples available:
Debugbar::startMeasure('render','Time for rendering');
Debugbar::stopMeasure('render');
Debugbar::addMeasure('now', LARAVEL_START, microtime(true));
Debugbar::measure('My long operation', function() {
// Do something…
});
Exceptions
debugbar-exceptions
The next tab is an exceptions logger. You can log exceptions to the debugbar by using code like this:
try {
  throw new Exception('foobar');
} catch (Exception $e) {
  Debugbar::addException($e);
}
Views
Laravel debugbar views
Views will show you all the templates rendered as well as include all the parameters passed into them. This is really handy as your application grows and you have numerous views. With this, you can be sure you are sending just the data your view actually needs, and lots of other use cases.
Route
Laravel Debugbar Route
Magically see everything related to the route being called. The URI, controller, file path, and namespace.
Queries
Laravel Debugbar Queries
Queries are one of the important parts for a lot of apps. I’ve seen apps not utilize eager loading and end up with a huge number of queries.
To give you a real world example I was tasked with building a back office style report for an e-commerce system. I was able to get the report working on my dev machine with seed data but as soon as I seeded real data the page took 20+ seconds to load. Browsing the queries tab in debugbar showed me exactly where my problem was.
Mail and Request
These two include everything you need to know about emails going out and the current request.
Folder Icon
Laravel Debubar Open
I’m not sure the “real” name for this, but by clicking the folder icon you can see all previous requests. This is useful when performing ajax calls so you can get more information on the actual requests.

Going Further

In this post, I only outlined the basics of what the Laravel Debugbarincludes. It has many more features under the hood including twig integration, enabling/disabling at runtime, and bridge collectors. If you want to go further the docs cover a lot of the underlying code in more details.
This is a package I highly recommend.

reference :https://laravel-news.com/2015/02/laravel-debugbar/

2015年11月23日 星期一

AngularJS: Getting around ngApp limitations with ngModule

As you AngularJS application gets more complex you will likely come to discover that the ngApp directive has two fairly big limitations:
  1. You can only have one ng-app per page.
  2. You can only associate a single module with a single HTML element

Combine modules into a single module

One way to work around this is to “combine” multiple modules into a single module by referencing them in another module. Here is an example of what I mean:


    
        
        
    
ng-app="CombineModule">

myDiv1
ng-controller="MyControllerA"> {{name}}

myDiv2
ng-controller="MyControllerB"> {{name}}
That works, but it has it’s problems. One it’s less clear the second div myDiv2 only needs the controller from MyModuleB why combine everything. You can imagine it would become less clear as your app and therefore the number of modules grows.
Also this example works because the controllers have different names, what if they had the same names. Being able to associate different modules with different HTML elements would give us better control of our namespace.

Do it programmatically using angular.bootstrap()

You might be surprised to find out that the limitations of the ngApp are not limitations of Angular itself. Angular allows you to associate more than one module per HTML element. Angular also allows you to have multiple HTML elements on a page associate with modules. You just have to do it grammatically.
Below is an example of how to do this. In this example we have two modules each with one controller. myDiv1 is associated with both modules. WhilemyDiv2 is associated with just with a single module.


    
        
        
    
id="myDiv1">

myDiv1
ng-controller="MyControllerA"> {{name}}
ng-controller="MyControllerB"> {{name}}
id="myDiv2">

myDiv2
ng-controller="MyControllerB"> {{name}}
The output of that code is:
    myDiv1

    Bob A
    Steve B

    myDiv2

    Steve B
You can see for yourself and play around with that code at:
This gives us a lot of flexibility, the problem is it’s pretty ugly. You have to reference the element itself in your code which means you are coupling your code with the HTML. That goes against one of the main goals of Angular.

Ideal solution: A more robust ngApp (enter ngModule)

The ideal solution would be for ngApp to allow you to do everything angular.bootstrap() allows you to do. Allow you to use it on multiple HTML elements. Allow you to specify more than one module.
Normally the solution to this would be to create your own Angular directive. The problem is, how would you define that directive? You would need a module to define it in which would defeat the purpose.
To implement a directive like ngApp you would need to implement it the way ngApp is implemented. I’ll spare you the trouble, I’ve already implemented it. You can download it from this link: angular.ng-modules.js
You can also find it on GitHub at:
https://github.com/luisperezphd/ngModule
This JavaScript file introduces the ngModule directive. Here is an example of how you would rewrite the code above to use ngModule:


    
        
        
        
    
ng-modules="MyModuleA, MyModuleB">

Module A, B
ng-controller="MyControllerA"> {{name}}
ng-controller="MyControllerB"> {{name}}
ng-module="MyModuleB">

Just Module B
ng-controller="MyControllerB"> {{name}}

Notes about ngModule

You might have noticed that in one case I use the plural version of the directive ng-modules with the “s” and in another case I use the singular version without the “s” ng-module.
This was just a preference of mine. I allow for both spellings interchangeably regardless of whether you reference a single or multiple modules. I just liked how it read better.
In keeping with Angular’s convention I allow you to use any variation of the directive name. For example, the following are all valid: ng:modulex-ng-modulesdata-ng-modules, etc.
Finally you should know that while you can now associate multiple HTML elements on a single page with modules by using this directive. Those HTML elements cannot be nested. If they are nested they will not behave properly. Said another way if you associate an HTML element with a module, you can associate a child of that element with another module.

Why the ngApp limitations?

One questions that I’ve seen asked in several forums is why did the Angular team place those limitations on ngApp to begin with. After all as I mentioned above the Angular framework itself does not have those limitations. I haven’t seen an answer from the Angular team but I can speculate.
Earlier versions of angular have the “view” and “route” functionality built in. In fact, that seemed the be the expected or recommended way to use Angular. Since you only have one URL, you can’t have multiple multiple views and routes on the same page. Therefore there might have been little need to be able to associate multiple modules.
They might have felt that having a single module associated with a page made it easier to understand and use. After all you often hear Angular often being mentioned as a technology for single page applications.
They might have simply not gotten around to it since two approaches already exists for doing it. I covered them above.
They might have felt that that kind of information belongs in your code, not your markup. While all these reasons are debatable, I think this one would be the most debatable since it’s possible for a module to only contain directives for front end controls.
I mentioned above that AngularJS does not allow nesting. Meaning you can’t have a element and a child element associated with different modules. The Angular team might have felt that because of that limitation it was better to avoid the situation by only allowing one module in your HTML.

refer : http://www.simplygoodcode.com/2014/04/angularjs-getting-around-ngapp-limitations-with-ngmodule/

Email activation with Laravel5

TODAY’S GOAL: To set up user registration via email activation
It’s week one of my journey and I’m feeling positive! I have a plan and I’m ready to go. After having installed Laravel I’ve decided that the first thing I’m going to work on is the user authentication side of things.

Registering a user via email confirmation

Out of the box Laravel 5 actually does all the user authentication for you, I really have very little to do. But one piece of functionality I do want to add in is making sure the user confirms registration by clicking on a link I send to their email. The primary reason for this is to prevent spam accounts being created. Let me show you how I did it.
The way this will work is as follows:
  1. A user registers an account.
  2. They are sent an email.
  3. User clicks on link in email and account is activated.
  4. User gets logged in.

Update the Users table

The first thing to do is update my users table to include a column to hold an activation code and also a column to set an account to active. I run the following command:
php artisan make:migration update_users_table
Laravel will then create the required migration file, I then update the up method to look like this:
public function up()
{
Schema::table('users', function(Blueprint $table)
{
$table->string('activation_code')->after('password');
$table->integer('active')->default(0)->after('activation_code');
});
}
This will update my users table with what I need. The after method which I chain to the end simply tells the migration to add the column after a specific field.
I ran the following command in the console…
php artisan migrate
and from a database perspective I’m all done, now I can store an activation code and active status on the users table.

Modifying the authentication trait

The next step is to modify the registration process. Typically when a user gets registered they are logged in and redirected to the home page, I want to add in the extra step requiring email confirmation. I found this to be a straight forward process.
The following file handles the registration process:
vendor/laravel/framework/src/Illuminate/Foundation/Auth/AuthenticatesAndRegistersUsers.php
Editing vendor files is not generally considered good practice but for the sake of speed I decided to brake that rule for now (I will refactor this I promise and update this post accordingly!!).
My postRegister method now looks like this:

public function postRegister(Request $request)
{
$validator = $this->registrar->validator($request->all());
if ($validator->fails())
{
$this->throwValidationException(
$request, $validator
);
}
$activation_code = str_random(60) . $request->input(’email’);
$user = new User;
$user->name = $request->input(‘name’);
$user->email = $request->input(’email’);
$user->password = bcrypt($request->input(‘password’));
$user->activation_code = $activation_code;
if ($user->save()) {
$data = array(
‘name’ => $user->name,
‘code’ => $activation_code,
);
\Mail::queue(’emails.activateAccount’, $data, function($message) use ($user) {
$message->to($user->email, ‘Please activate your account.’);
});
return view(‘user.activateAccount’);
}
else {
\Session::flash(‘message’, ‘Your account couldn\’t be create please try again’);
return redirect()->back()->withInput();
}
}
Normally after registration the user is logged in and redirected, but I’ve made a few modifications.
Allow me to explain what I did here:
  1. After a user submits a registration form they are sent to this method
  2. If validation is successful I generate a random string (activation code) and a user object
  3. I store these values in the users table
  4. After saving the data I use the Mail facade and email the user, passing through the activation code
You’ll notice I have a backslash in front of each Facade when I use it… Don’t forget that Laravel 5 makes use of proper namespacing, this was a really frustrating thing to debug. The backslash refers to the root namespace of the application where the Facades live.
Now the user has a new email in their inbox :)

Add in a new route and modify Auth controller

At this point it was time to add in a new route to handle the link that gets clicked in the email which looked like so:
Route::get('activate/{code}', 'Auth\AuthController@activateAccount');
When the user clicks on the link they go to the below function which looks like:
public function activateAccount($code, User $user)
{
   if($user->accountIsActive($code)) {
\Session::flash('message', 'Success, your account has been activated.');
return redirect('home');
}
\Session::flash('message', 'Your account couldn\'t be activated, please try again');
return redirect('home');
}
This function checks to see if the user is active and redirects accordingly. I’ve further abstracted that logic and store the accountIsActive method in my User model:

public function accountIsActive($code) {
$user = User::where('activation_code', '=', $code)->first();
$user->active = 1;
$user->activation_code = '';
if($user->save()) {
\Auth::login($user);
}
return true;
}
So basically the user clicks on the link in the email, the above method gets their record from the database, sets their active status to 1 and then logs them in. I also added the following snippet to my Authenticate.php middleware file so that only active users could view authenticated data.
if (!\Auth::user()->active) {
\Session::flash('message', 'Please activate your account to proceed.');
return redirect()->guest('home');
}

Email registration activation summary

I’m happy with my start on this app, I’ve spent about 3 hours so far to get it where it is, I know I need to do some refactoring soon but at least it’s a decent start. This first week has been spent doing a lot of research on what’s new with Laravel 5 and as such I’ve probably spent less time coding and more time studying. Over the next few weeks I hope to speed things up a bit.
This past week I’ve spent a lot more time than I wanted simply debugging small bugs as I’m still getting familiar with Laravel 5, it’s been annoying and the documentation on the web is still playing catch ups but hey that’s all part of the challenge right?
That’s it for now I hope you enjoyed, stay tuned as my next step is to integrate social media logins using Socialite.

refer : http://www.codeanchor.net/blog/email-activation-laravel/
github : https://github.com/iateadonut/laravel5-email-authentication

Appendix :
'encryption' => 'tls' or 'encryption' => 'ssl'
"port 465 (with SSL) and port 587 (with TLS)"

wibiya widget