Because of backwards compatibility foreign key checking is by default disabled in SQLite databases. As current Laravel 4 version does not provide any elegant way of enabling that, a little hack is required to force foreign keys for SQLite connections.

Database seeding is a convenient way to fill Laravel 4 application with test data, this can be useful while application developing, or testing. In provided example ‘users’ table will be seeded with test user data. Example table was previously created with Laravel Migrations which is described in this post.

First create seeding class for the table under app/database/seeds directory, in this case UserTableSeeder.php

Method run() deletes all existing users, then creates new user row with provided name, email and password (hashed with Hash::make() function). Please note that ‘User::create’ requires User model to be set up. By default User model is created in app/models, so there is no need of doing that in this particular case.

Next we need to add new seeder class to app/database/seeds/DatabaseSeeder.php

Laravel 4 migrations provides a convenient way of versioning changes in application database structure. It uses Laravel Schema Builder to store database structure in php classes, this structure is then utilised to create/alter/delete database tables in database that is currently used by application. Schema Builder is database type independent, so any database supported by Laravel can be used. This makes extremely easy to change database type, and keep the same tables structure (for instance from MySQL to SQLite).

Database schema should be altered if any change in database structure has to be done. This way all developers can use the same schema version, as php files can be easily stored in version control system. One important thing to notice about migrations: always create new migration file when you want to alter existing table. Migration class that was used should not be changed.

Let’s create simple ‘users’ table with migrations. Table should contain: id, name, email, password, remember_token, created_at and updated_at fields. First thing to do is set up database connection, this should be done by altering app/config/database.php file. The most commonly MySQL will be used, this requires to set username, password, host, and database name in ‘mysql’ array. When database connection is set up go to project’s root directory, and run:

$ php artisan migrate:make create_users --create --table=users

This command will create a new migration file for users table in app/database/migrations directory (by default). File name contains current date, time, and underscored class name provided after ‘migrate:make’ (create_users). Full path to the file is in my case app/database/migrations/2014_08_10_131305_create_users.php. Edit this file to provide users table fields and details. Remember to always use artisan commands to create migration files, don’t create them manually.

CreateUsers class has 2 methods: up() and down(). Up is being called when ‘php artisan migrate’ command is run (this creates/alters table), down() is being called when ‘php artisan migrate:rollback’ is run (this rollbacks last migration, so deletes users table in this particular case).

One of the php disadvantages is that internal PHP functions uses built-in error reporting system, while object oriented extensions use exceptions. In this article I’ve presented custom Codeigniter class that handles all uncaught exceptions thrown during a runtime. That solution works sufficiently with modern code, but standard php errors are not under its control. My aim was to handle all system wide errors and exceptions within just one class and in the same way.

A simple solution to achieve this is to use set_error_handler() function. It’s similar to set_exception_handler(), but expects error details instead of exception object. When handler function is called, it throws new ErrorException with error details passed to the construct. This simple modification translates every ocurred error into uncaught exception, so php errors and exceptions are treated exactly the same way. Functions like printException() and logException() can be reused, so there is no need to write new functions just for regular errors purpose.

Another issue is controlling which errors should be handled. I’ve decided to check the occured error level against current error_reporting value, if bitwise ‘and’ result is 0, then error is just ignored. This allows you to set error_reporting(E_ALL ^ NOTICE) to ignore all notices, just like in default php error handling mechanism.

One signifficant thing to notice while using this solution is that every error handled by provided class will stop the script. So if you have error_reporting(E_ALL) set, every notice/warning will terminate the script. This happens because execution will always stop after the exception_handler is called.

Codeigniter framework provides number of useful functions for Error Handling (described on http://ellislab.com/codeigniter/user-guide/general/errors.html). One of them – log_message(‘level’, ‘message’) writes a new log line to /application/logs/[log file name]. Great adventage of using this solution is that developer doesn’t have to create (open, close etc.) log files on filesystem. Just one function does the job.

Codeigniter itself doesn’t provide any built-in method to use custom PHP interfaces. So if you want to implement some in your class, this requires a little hacky solution.

First create an extension class for Codeigniter loader. This will let you load interfaces using $this->load->iface() method (‘interface’ is a reserved PHP word, so it can’t be used as a function name). File path should be: /application/core/MY_Loader.php

To implement a particular interface in your class just load it right before the class beginning. In this case it’s loaded in model file, so get_instance() finction must be used instead of $this variable.

This post shows an example controller class which allows you to log in to Codeigniter application via external oAuth 2 system like facebook or google. It uses multi-provider oAuth 2 client package from Sparks repository. Sparks is a package management system for Codeigniter that allows you to install external libraries. I recommend to do it with ssh, but there is also a possibility of manual installation for those who can’t use shell.

You can install oAuth 2 package from http://getsparks.org/packages/oauth2/versions/HEAD/show

Things to notice about oAuth 2 package:

1. It uses url helper, so you should load it (I recommend auto loading – http://ellislab.com/codeigniter%20/user-guide/general/autoloader.html, url helper is one of the most commonly used Codeigniter helper), otherwise the following error will be shown:

Fatal error: Call to undefined function site_url() in /sparks/oauth2/0.4.0/libraries/Provider.php on line 76

2. I’ve found a bug in /sparks/oauth2/0.4.0/libraries/Provider/Blooie.php, function url_access_token() is not closed (just add } afterwords to fix it).
Not many use blooie, thats why this is not fixed yet I guess 🙂

3. Codeigniter session must be initialized, see http://ellislab.com/codeigniter%20/user-guide/libraries/sessions.html

Every oAuth service must provide you with an id, and secret string to make you use it. That usually requires to register an app in oAuth provider system. Presented class reads provider data from config file (db is also a good or even better idea). The following is an empty example for facebook and google credentails stored in /application/config/config.php:

You should obviously fill it with a proper data taken from oAuth provider. Nice thing about this solution is when you want to add new oAuth service, there is no need to modify anything more than config file, (much better than hardcoding it within class file).

My goal is to let user just click on facebook or google icon, and be logged. During the first visit user must always accept permissions of our app, and that’s it. If user is visiting controller and agrees for permissions for the first time, than a new user (db row) will be created. During next login the user will be loaded from db, basing on oAuth user id (taken from a provider), and the name of a service. These two variables are always unique together, so it is safe to base on that set of credentials.

Path to run controler is /login/oauth/{providerName} considering mod_rewite being activated. I use my own User model, and SessionManager library, but because of the comments it should be easy to understand what they do.

While developing web applications I use php exceptions model for handling errors, which is similar to ones used in java and other objective languages. When an error occurs you can throw an exception, then an Exception object is created. Exception can then be caught somewhere else in the code, where you can decide what to do in case of a particular error, here an exception object can be used to read details about the error. You can also create your own Exception class, or use one of the existing e.g. in SPL (see http://www.php.net/manual/en/spl.exceptions.php). This helps you recognize which kind of error occured, not just if (you can throw many exceptions in one function), and write many variants of application behaviour for different kinds of errors (exceptions thrown). Everything is explained in php manual (http://php.net/exceptions), read for details.

My problem was that very often my exception was caught just to be passed to the error class (then write to log file, print on screen etc.). I didn’t like repeating try/catch section of the code looking like this:

In the above example Error class construct should be considered as an exception handler.

Built-in php (obviously 5, I believe nobody uses php 4 nowadays) set_exception_handler function comes of help. It lets you define a handler function used if an exception is not caught within a try/catch block. Presented ExceptionHandler class is a Codeigniter library, it should be auto loaded so handle function is always set as default handler (in constructor). Handle must be public, otherwise set_exception_handler won’t work. Class also contains functions for printing and logging exceptions details (you can add whatever you want to happen when your system is in trouble). You can obviously use it for handling exceptions in try/catch blocks, but it’s not necessary. Once library’s loaded, it’s object is already created under $this->librarynamenocapitals, so ‘manual’ run looks like this:

You can also add other behaviours to this class such as: send email to admin, or return just particular answer code (nice in REST web services). You can change this depending on ENVIRONMENT constant mode (set in index.php, you should know this before writing anything in Codeigniter).