找回密码
 注册

QQ登录

只需一步,快速开始

BCM 门户 IT世界 资料备录 查看内容

Introduction to Laravel Framework

2014-1-13 15:12| 发布者: Test| 查看: 801| 评论: 0|来自: laravel book

摘要: This book is about Laravel, a web application development framework that saves you time and effort and makes web development a joy. Laravel has shaken up the PHP community in a big way - especially wh ...
a simple guestbook application with Laravel framework


Let’s re-build the guestbook app from scratch using the Laravel framework. We will create a new database named “laravel_guestbook”.

I’ll assume you have Laravel installed in your local machine (installation of the Laravel framework will be discussed in a later lesson). Next open up the database.php file in the app/config directory of your Laravel application. Make sure that the default key is set to mysql:

return array(
        ...
        'default' => 'mysql',

Then enter your database information:

...
'connections' => array(
        'mysql' => array(
                'driver'    => 'mysql',
                'host'      => '127.0.0.1',
                'database'  => 'laravel_guestbook',
                'username'  => 'Your_Database_Username',
                'password'  => 'Your_Database_Password',
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
        ),
...

It’s good practice to use migrations to track the changes in the database. You may think of Laravel migrations as version control for your databases. In order to use migrations, you first have to allow Laravel to create a special table in your database (this table is used by Laravel internally to to track the migrations that are executed).

We will use the Laravel Artisan command-line utility to install migrations in our database. Open a terminal at the root folder of your laravel application and execute the following command:

$ php artisan migrate:install
Nice! Now we're ready to do some migrating!

Once that’s done we’ll create the migration file that will create our entries table:

$ php artisan migrate:make create_entries_table
Migration created successfully!

Laravel will generate a new migration file (mine is named 2013_01_04_103348_create_entries_table.php) in the app\database\migrations folder. Let’s edit this file and define the schema for our entries table:



use Illuminate\Database\Migrations\Migration;

class CreateEntriesTable extends Migration {

        /**
         * Run the migrations.
         */
        public function up()
        {
        Schema::create('entries', function($t) {
          $t->increments('id');
          $t->string('username', 50);
          $t->string('email', 100);
          $t->text('comment');
          $t->timestamps();
        });
        }

        /**
         * Reverse the migrations.
         */
        public function down()
        {
                Schema::drop('entries');
        }
}

The up() method contains what you want to do to the database when you execute the migration. It will normally contain an array of column definitions to be created on the table. In our case, it contains the schema for our entries table. The down() method will contain what you want to do when you rollback or “undo” the migration.

Let’s switch to the terminal and execute the migration to actually create the table in the database:

$ php artisan migrate
Migrated: 2013_01_04_103348_create_entries_table

If you check your database, you’ll find Laravel has created the entries table for us:

CREATE TABLE `entries` (
        `id` INT(11) NOT NULL AUTO_INCREMENT,
        `username` VARCHAR(50) NOT NULL,
        `email` VARCHAR(100) NOT NULL,
        `comment` TEXT NOT NULL,
        `created_at` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
        `updated_at` TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00',
        PRIMARY KEY (`id`)
);

Now we will create a Laravel data model class that represents the table described above. Our database table is called “entries”, so we will call our model class “Entry”. Let’s create a new PHP file app/models/Entry.php and paste the following code:



class Entry extends Eloquent {

        /**
         * The database table used by the model.
         *
         * @var string
         */
        protected $table = 'entries';

}

Taking a look at this file shows there isn’t much there. However, the functionality of our Entry class is slightly deceiving, because this model inherits all the functionality built into the Laravel Eloquent class. Your Entry model controls everything that goes in and out of the entries table we created. The Eloquent parent class that Entry inherits from is a high-level database abstraction layer. This layer is known as an “object relational mapper” because it maps each model directly to a database table.

Let’s give this application a face by creating the view template file. In Laravel, all template files are stored in the app/views folder. Laravel comes equipped with its own templating engine called the Blade templating engine. Blade templates files have the extension .blade.php. Let’s create a new file named home.blade.php in the app/views folder:



    </span>Laravel Guestbook<span style="color:#070">


    @foreach($entries as $entry)
      

{{ $entry->comment }}

Posted on {{ $entry->created_at->format('M jS, Y') }} by href="mailto:{{ $entry->email }}">{{ $entry->username}}

/> @endforeach action="/" method="POST"> border="0"> Name type="text" name="frmName" value="" size="30" maxlength="50"> Email type="text" name="frmEmail" value="" size="30" maxlength="100"> Comment name="frmComment" rows="5" cols="30"> type="submit" name="submit" value="submit"> type="reset" name="reset" value="reset">

This is essentially the same HTML code we wrote earlier in the plain PHP version. The only difference is that, here we’re using Laravel Blade template syntax e.g. @foreach($entries as $entry). As you may have guessed, @foreach is just like the foreach operator that we use in plain PHP to iterate over an array. In this case we’re iterating through all the guestbook entries in the database. {{ $entry->comment }} is the Blade syntax for PHP’s echo keyword. In this example, {{ $entry->comment }} is literally translated into comment; ?>

Of course all the data that we are iterating through aren’t directly available in the view, we will have to pass the data to the view using the controller which will render this view. And that’s what were going to do next.

Let’s create a controller class to handle the business logic of our guestbook app. Since the primary responsibility of this controller is to store and retrieve records from the entries table, we’ll name it EntriesController. Laravel requires that you place all your controller classes in the app/controllers folder. Let’s create a new file named app/controllers/EntriesController.php and paste the following skeleton code:



class EntriesController extends BaseController {

        # Handles "GET /" request
        public function getIndex()
        {
        }

        # Handles "POST /"  request
        public function postIndex()
        {
        }

}

Controllers in Laravel usually descend from the BaseController super-class. By convention, controller method names in Laravel have the following syntax:

Name of the HTTP verb (in lowercase) + Name of the action (in Pascal-case)

For instance, if we want to handle the request GET /page, our controller method will be named getPage(). Likewise, if we wanted to handle POST /email and PUT /file our controller methods will named postEmail() and putFile() respectively.

Returning to our guestbook sample app, we want our controllers to respond to GET / and POST / requests; in other words, we wish to handle reqests for the “index” page. Therefore, we have named our controller methods getIndex() and postIndex() respectively.

Let’s first implement the controller for the HTTP GET / request:

public function getIndex()
{
        return View::make('home')->with('entries', Entry::all());
}

The above code snippet loads a view template named “home” and passes a variable named $entries to the template. Laravel automatically maps the “home” view to the app/views/home.blade.php template file. The $entries variable contains all rows from our entries database table. Recall that the table is represented by our Entry model class; the Entry::all() method retrieves all records from the database table it represents. Laravel then transforms the “home” template to a fully functional HTML web page and returns it to the user’s browser.

Now that we have a functioning HTML form, let’s implement the POST / controller:

public function postIndex()
{
    // get form input data
    $entry = array(
        'username' => Input::get('frmName'),
        'email'    => Input::get('frmEmail'),
        'comment'  => Input::get('frmComment'),
    );

    // save the guestbook entry to the database
    Entry::create($entry);

    return Redirect::to('/');
}

We’ll step through each segment of the code:

$entry = array(
    'username' => Input::get('frmName'),
    'email'    => Input::get('frmEmail'),
    'comment'  => Input::get('frmComment'),
);

Inside the method, we first have to get what the user has inputted in the HTML form. Laravel allows as to do that using the Input::get('form_field_name') method where the form_field_name is the name of the input field. For instance, we have an input field named “frmName” in our HTML form: . The Input::get('frmName') method will return whatever data the user had entered in that textbox. In the above snippet, we gather all relevant form data into the $entry array. Take note that the array keys above exactly match the column-names of our entries table.

Entry::create($entry);

Inserting Eloquent models into your tables couldn’t be easier. We call the Eloquent::create() method which will insert a new record into the database for us - this method will extract the column-names from the associative array and automatically populate all database columns. Contrast the above line of code with the tedious SQL query and the multiple MySql API methods we had to write in our previous plain PHP guestbook app.

return Redirect::to('/');

After all work is done, we return a HTTP 302 redirect response to send the user back to our homepage; essentially, we’re transferring the request to the getIndex() controller.

Here’s the app/controllers/EntriesController.php file in its entirety:



class EntriesController extends BaseController {

        public function getIndex()
        {
                return View::make('home')
                        ->with('entries', Entry::all());
        }

        public function postIndex()
        {
            // get form input data
            $entry = array(
                'username' => Input::get('frmName'),
                'email' => Input::get('frmEmail'),
                'comment' => Input::get('frmComment'),
            );

            // save the guestbook entry to the database
            Entry::create($entry);

            return Redirect::to('/');
        }

}

We’re almost done with our application. We must let Laravel know about our EntriesController. Let’s open up the file app/routes.php and register our controller class by pasting the following code:



Route::controller('EntriesController', '/');

Here, we register our controller with the index URL (“/”).

It’s a good idea to generate PHP autoload files at this stage. We will use the composer command-line utility to do that:

$ composer dump-autoload

That’s it! We have just created our first Laravel application. Here’s the Laravel-powered guestbook app in it’s full glory:



鲜花

握手

雷人

路过

鸡蛋

相关阅读

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )

GMT-8, 2026-4-12 15:16 , Processed in 0.015777 second(s), 18 queries .

Supported by Weloment Group X3.5

© 2008-2026 Best Deal Online

返回顶部