Giới thiệu Slim PHP

Slim là một framework PHP, chủ yếu sử dụng cho các ứng dụng web và API theo cấu trúc REST (Representational state transfer). Các framework PHP khác cũng có thể thực hiện chức năng tương đương như CakePHP, CodeIgniter…. Tuy nhiên đúng như tên gọi, ưu điểm của Slim chính là kích thước nhỏ gọn, dễ dàng cài đặt và triển khai. Bài viết xin giới thiệu tóm tắt về Slim PHP và ứng dụng đơn giản kết hợp giữa Slim PHP và AngularJS

1. Cài đặt Slim PHP

Tài liệu về Slim có thể tìm thấy tại : http://docs.slimframework.com/

Cách cài đặt tùy chọn : cài đặt qua Composer hoặc tải code từ địa chỉ Github : https://github.com/slimphp/Slim (ví dụ minh họa dung cách này)

2. Ứng dụng Slim kết hợp AngularJS

Minh họa cho việc sử dụng Slim, chúng ta tạo một ứng dụng quản lý công việc với các chức năng cơ bản : tạo mới, sửa xóa

2.1. Bảng dữ liệu khởi tạo :

CREATE TABLE IF NOT EXISTS `tasks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(150) NOT NULL,
`description` text,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

INSERT INTO `tasks` (`name`, `description`) VALUES (‘Angular’, ‘Install Angular’), (‘Php’, ‘Install Slim php’);

2.2. Khai báo API xử lý qua javascript :

AngularJS được sử dụng là phiên bản 1.3.15 : https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js

angular.module('CrudApp', ['ngRoute']).
    config(['$routeProvider', function ($routeProvider) {
        $routeProvider.
        when('/', {templateUrl: 'assets/tpl/lists.html', controller: ListCtrl}).
        when('/add', {templateUrl: 'assets/tpl/add-new.html', controller: AddCtrl}).
        when('/edit/:id', {templateUrl: 'assets/tpl/edit.html', controller: EditCtrl}).
        otherwise({redirectTo: '/'});
}]);
function ListCtrl($scope, $http, $location) {
    $http.get('api/tasks').success(function (data) {
        $scope.tasks = data;
     });
     $scope.del = function (index, id) {
         var deleteTask = confirm('Are you sure you want to delete?');
         if (deleteTask) {
             $http.delete('api/tasks/' + id);
             $scope.tasks.splice(index, 1);
         }
     };
}
function AddCtrl($scope, $http, $location) {
    $scope.master = {};
    $scope.activePath = null;
    $scope.add = function (task, AddNewForm) {
        $http.post('api/add', task).success(function () {
            $scope.reset();
            $scope.activePath = $location.path('/');
        });
        $scope.reset = function () {
            $scope.task = angular.copy($scope.master);
        };
        $scope.reset();
    };
}
function EditCtrl($scope, $http, $location, $routeParams) {
    var id = $routeParams.id;
    $scope.activePath = null;
    $http.get('api/tasks/' + id).success(function (data) {
        $scope.tasks = data;
    });
    $scope.update = function (task) {
        $http.put('api/tasks/' + id, task).success(function (data) {
            $scope.tasks = data;
            $scope.activePath = $location.path('/');
        });
   };
}

2.3.  Các hàm xử lý qua Slim

  • Khởi tạo

require 'Slim/Slim.php';
 \Slim\Slim::registerAutoloader();
 $app = new \Slim\Slim();
  • Lấy danh sách

Hàm js tương ứng : ListCtrl
Đường dẫn : /api/tasks
Phương thức : GET
Kết quả trả về dưới dạng JSON

$app->get('/tasks', function () {
    $sql = "select * FROM tasks ORDER BY id";
    try {
         $db = getConnection();
         $stmt = $db->query($sql);
         $results = $stmt->fetchAll(PDO::FETCH_OBJ);
         $db = null;
         echo json_encode($results);
    } catch(PDOException $e) {
         echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
});
  • Tạo mới

Hàm js khai báo : AddCtrl
Đường dẫn : /api/add
Phương thức : POST
Trả về dữ liệu JSON của đối tượng mới tạo

$app->post('/add', function() use ($app) {
    $request = $app->request();
    $task = json_decode($request->getBody());
    $sql = "INSERT INTO tasks (name, description) VALUES (:name, :description)";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("name", $task->name);
        $stmt->bindParam("description", $task->description);
        $stmt->execute();
        $task->id = $db->lastInsertId();
        $db = null;
        echo json_encode($task);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
});
  • Cập nhật

Hàm js khai báo : EditCtrl
Đường dẫn : /api/tasks/{id}
Phương thức : PUT
Trả về dữ liệu JSON của đối tượng sau khi sửa đổi

$app->put('/tasks/:id', function ($id) use ($app) {
    $request = $app->request();
    $task = json_decode($request->getBody());
    $sql = "UPDATE tasks SET name=:name, description=:description WHERE id=:id";
    try {
        $db = getConnection();
        $stmt = $db->prepare($sql);
        $stmt->bindParam("name", $task->name);
        $stmt->bindParam("description", $task->description);
        $stmt->bindParam("id", $id);
        $stmt->execute();
        $db = null;
        echo json_encode($task);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
});
  • Xóa dữ liệu

Hàm js khai báo : ListCtrl
Đường dẫn : /api/tasks/{id}
Phương thức : DELETE

$app->delete('/tasks/:id', function ($id) {
    $sql = "DELETE FROM tasks WHERE id=".$id;
    try {
        $db = getConnection();
        $stmt = $db->query($sql);
        $results = $stmt->fetchAll(PDO::FETCH_OBJ);
        $db = null;
        echo json_encode($results);
    } catch(PDOException $e) {
        echo '{"error":{"text":'. $e->getMessage() .'}}';
    }
});
  • Để kết thúc khai báo phương thức của Slim

$app->run();

3. Kết luận

Bài viết đã tổng hợp việc kết hợp Slim và AngularJS trong 1 ví dụ cơ bản gồm các chức năng thêm, sửa, xóa.

Chi tiết code cài đặt của ví dụ : https://github.com/trvinhlong/todo_slim.git

Tài liệu tham khảo :

http://docs.slimframework.com/
http://slimframework.com/
http://www.blog.iamaronbarbosa.com/building-a-basic-crud-application-using-angularjs-and-slim-php-framework-part-1/

Add a Comment

Scroll Up