I'll preface this with saying that I'm a crappy programmer, I'm sure that what I want to do could be done in 10 lines of node or Rails or something else, but PHP is what I have available.
So, I'm hoping to find a simple PHP library which wraps the database calls in an API that looks similar to the RESTful model.
I've had little success trying to find such a thing -- searching for PHP CRUD or PHP REST turns up several zillion pages, and I've no idea how to filter through them.
I'm really trying to keep things simple here, I don't want a big framework like Zend or something. The models I'm dealing with in Backbone are really simple. I just want to send GETs to, say, /notes/3 or POSTs to /notes, etc, and have PHP do the right thing to a database.
Perhaps I'm asking too much, but it seems to me that this is what other frameworks like Rails provide. Any suggestions? TIA...
EDIT Nov 2018: Although I wouldn't knock CodeIgniter, nowadays Laravel (currently 5.5) is the framework I use.
Here is a good article that sums up the reasons I use Laravel.
To get jump started, I recommend Laracasts. It's a subscription video tutorial service that goes in depth on how to use Laravel (and other web dev related things).
ORIGINAL ANSWER:
Codeigniter, to me, is the easiest of the Rails-like frameworks. It's bare bones, and you can build a CRUD app from scratch easily.
The biggest issue with rolling your own app is security. Codeigniter can help you build a less hackable site by shielding you from many of the common security risks, such as using $_POST arrays directly, and not properly filtering your data. Not to mention the many helper classes it offers such as form validation.
You can view the documentation on their website. It's very easy to use as long as you remember the navigation is hidden at the top of each page. :D
Do you understand how CRUD works internally? From a PHP standpoint, it could be as easy as having a switch statement over each REST call possibility.
See this page here:
http://www.codethinked.com/building-epic-win-with-backbone-js
Skip to the section titled "Wiring It Up To The Server".
Your PHP script simply has to satisfy those requirements.
A simple prototype code:
switch($_SERVER['REQUEST_METHOD']){
case 'POST':
// create new item
break;
case 'GET':
// get item(s)
break;
case 'PUT':
// update item
break;
case 'DELETE':
// delete item
break;
}
You will also need to set up a .htaccess file as follows (to handle accessing non-existent urls):
# Turn on rewrite engine and redirect broken requests to index
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-l
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* index.php [L,QSA]
</IfModule>
A URL like http://mysite.com/1 doesn't real exist, which is why you need to route.
Edit: In case you are planning to use PUT or DELETE in HTML forms, forget it. As of writing this, it has not been accepted in HTML5, and pretty much all browsers fail to support this. My "fix" to this is to use GET for GET requests, and POST for all the rest (POST itself, PUT and DELETE). Example:
<form action="POST" action="/users/5">
<input type="hidden" name="method" value="DELETE"/>
<button>Delete User #5</button>
</form>
This, however, is not a problem with AJAX since apparently you can set XMLHttpRequest Method to anything you want without problems.
There are lots of restfull frameworks for PHP, have a look here and here.
I personally like fat-free-framework but you need PHP 5.3 for it.
Also there is a lot of support for Tonic and Recess seems quite interesting.
Also all the standard frameworks have some sort of rest support (zend, code igniter, symfony and the likes)
You should find your fit ..
Also if you already have your mysql queries ready, you could convert the mysql results directly into json like this :
function recordSetToJson($mysql_result) {
$rs = array();
while($rs[] = mysql_fetch_assoc($mysql_result)) {
// you don´t really need to do anything here.
}
return json_encode($rs);
}
After that it's quite easy to associate with urls ..
From : Convert MySQL record set to JSON string in PHP
You can use silex https://github.com/fabpot/Silex a simple framework based on symphony 2. With Silex you can easily route and map action.
You have access to the basic CRUD element and you can call a function with the URL component.
There are some examples on the documentation :
http://silex-project.org/doc/usage.html
new REST api solution
examples
http://www.apifysnippets.com/
code
https://github.com/apify
tutorial
http://blog.fedecarg.com/2011/09/11/building-a-restful-web-api-with-php-and-apify/
UPDATE:
another rest solution for PHP:
http://luracast.com/products/restler/
:)
you might want to look at Slim:
http://www.slimframework.com/
its definitely light-weight and can give you what it seems like you're looking for, an easily deployed RESTful backend with php.
Related
I want to create a pure PHP REST API and I am quite new in backend development field, but I am experienced software developer, so some concepts are known to me.
However, after watching several tutorials on how to create REST API with PHP, all instructors were using simpler examples, where no nesting exists.
Simple Example:
GET /api/category/read.php
However, I want to create something like this:
GET /api/{user_id}/{folder_id}/{file_name}/read.php
I am struggling to find any tutorial covering this with PHP. And I have spent several hours trying to figure it out by myself by trying to modify the code I have seen in Tutorial videos. I mean if I do like they do, this would mean manually creating folders in my Project Folder for each {user_id} and so forth for each sub-folder... but I do not think that such hardcoding is the solution.
I have found some SO questions here relating closely to my question, but none have satisfying answers - makes me wonder that this if this is possible to do at all. But it seems so common (for example, I know that GitHub API has just that support /{user}/repos) so I think it should be doable.
I would be really grateful if someone could help me out how to accomplish my goal. If not else, pointing to a tutorial / documentation that does just that is equivalently appreciated!
You do not need to create the folder structure to achieve this. It would be more advantageous to use something like Apache Mod Rewrite or a framework like Laravel to help avoid the need to create the file structure you are describing and have a single endpoint for handling specific routes:
Using mod rewrite with Apache2 would work something like:
.htaccess
RewriteEngine On
RewriteBase /
RewriteRule ^api/(.+)/(.+)/(.+)/read /api/read.php?user_id=$1&folder_id=$2&file_name=$3
This would provide the URI variables in the $_GET and $_REQUEST supergobals in /api/read.php
Using the Laravel framework you can leverage their MVC approach and create dynamic routes which can capture the URL vars and deliver them to the desired Controller endpoint:
in your routes file:
Route::get('api/{user_id}/{folder_id}/{file_name}/read', Controller#read)
in the Controller:
public function read(user_id,folder_id,file_name){ /* do stuff */ }
There is alot more to know about the specifics of MVC and using Laravel to create an API, however, they have great documentation and tutorials.
Create a PHP script that receives every request (have Apache direct all requests to it), and then process the $_SERVER['REQUEST_URI'] variable to split the path into segments, storing the parts in variables of your choice. Then dispatch the request to sub-components as necessary.
I have been reading the article to learn how to build a rest API:
http://www.gen-x-design.com/archives/create-a-rest-api-with-php/
At one point it says "Assuming you’ve routed your request to the correct controller for users"
How can I do this without a framework?
I am writing a REST API that I can interact with from a different application. I ready the tutorial above, and it makes sense mostly, but I don't exactly understand what it means to route my request to the correct controller for users.
Assuming you are using Apache, you can accomplish this easily using a combination of mod_rewrite and some PHP-based logic. For example, in your .htaccess or vhost definition, you could route all requests through a single handler, possibly index.php:
# Don't rewrite requests for e.g. assets
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*+)$ index.php?q=$1 [L]
...then in your index.php file do something like:
$target = $_REQUEST['q'];
/* parse the request and include the appropriate controller PHP */
For example, a request for /products/1234 might result in a controllers/products.php handler being included. That handler could then act on product 1234. Because you're using REST, you shouldn't need to be concerned with the original request having a query string parameter.
There are multiple ways to accomplish what it sounds like you're trying to do, this is just one of them. Ultimately what you go with will depend on what your specific requirements dictate. The above pattern is fairly common however, many frameworks use it or something like it.
I think this is a matter of terminology. Every code with some level of generalization can be called "framework". And since you're asking about "routing", which provides a starting level of generalization, every implementation becomes a framework.
If you don't want to use existing fully-fledged frameworks, you can elaborate your own light-weight-implementation. Here is some articles to start:
Write your own PHP MVC framework
PHP MVC framework in one hour
(the author has decided to remove this post because he thinks that using a modern fully-fledged framework is more appropriate way of programming such things, yet some people find such simple and stripped-down approache more suitable in many aspects: learning, efficiency, no huge dependencies, etc); the post is available on some other sites, for example, in the wayback machine or copies
The Model View Controller in PHP
All these intros include explanations of the routing mechanizm and demonstrate its implementation.
Basically, a router is a kind of internal "DNS" (in a figurative sense) inside your application. When a request arrives to your site, you need to dispatch it to appropriate worker class, according to that request properties. This is the router's task.
i want to make a very simple website but with OOP PHP. I got enough experience in programming (c#, c++, php, js and more) so i know how to make classes etc, but the thing i dont understand with php is the correct way to call things.
there are hundreds of tutorials oop php on the internet but nothing with this (or maybe its a weird question :P).
let me explain.
for example i want a news website and i got a class News with the function create.
if i follow the url mywebsite.com/news/create or mywebsite.com/news?action=create i want to execute the php class News, action create.
but how am i suppose to do this. do i need to make in index.php
if(action == news) news->create();
and for every action another... i dont think so :P. so how can i make this correctly? or is it better to take a simple mvc framework?
Thnx,
Stefan.
I would use the CodeIgniter framework for this, it is EXTREMELY easy to install, plus it uses the the MVC design pattern.
Then to make your url like this: "mywebsite.com/news/create" you can change a simple thing in the htaccess file like such:
RewriteEngine on
RewriteCond $1 !^(index\.php|images|robots\.txt)
RewriteRule ^(.*)$ /index.php/$1 [L]
Source:
http://codeigniter.com/user_guide/general/urls.html
If on the other hand you don't want to use a framework, you can just use Apache's mod_rewrite to remove the script filename, then using php's explode function to get the function and parameters from the $_SERVER["REQUEST_URI"] variable.
There is a good example here:
http://www.phpaddiction.com/tags/axial/url-routing-with-php-part-one/
i know many frameworks and i worked with codeigniter, and yii. I prefer yii but the mean question for me is, is it possible to work without such frameworks and route things or is it better to take a framework.
Let it be known that I only have experience making websites with 5 or 6 pages. I'd like to make a PHP Gaming journalism site like http://www.escapistmagazine.com/
The first problem I can think of is that I would have to manually make a page for each game article; that path was obviously not going to work so I decided to store all the articles in a database.
The problem with storing the content in a database was figuring out how to retrieve them. I attached a GET variable to the url so I could retrieve any article from an index.php file; however, I could not hide the GET variable from the url so I ditched that method. I have no free cash to buy a CMS and I have tried free ones like Drupal to great frustration.
Do I have to generate a separate php file for each article? What would a professional/veteran do in my situation?
First, I'd like to state that if you are having trouble finding the patience to set up Drupal, Wordpress or similar free CMS', you would be hard pressed to find the patience to creating one from scratch.
Having said that, to address the specific request you're looking for, I believe you want to use mod_rewrite to funnel your requests through a single file, which would, in turn, hand the request off to the appropriate file. Drupal, for instance, uses the following rules:
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]
Which routes your URL into a single variable, 'q'.
I manage a CMS that publishes PHP pages statically like you're considering. Coming from MVC designs, it is horrific, and I highly suggest you not take that route.
I'd check into one of the frameworks like Code Igniter, Cake, or if you feel like you want to torture yourself, Zend. All joking aside, you'll be able to create routes that use the URL request to find the content that you're looking for. I won't go into the whole concept of MVC and routing here, as it is well documented throughout the web, but essentially it keeps template management much easier. As a matter of fact, pretty much everything is easier, and your codebase stays much cleaner.
Right now, I've got a codebase for my CMS of almost 400mb. This is because there's an abundance of static pages that are indexed. This would be cut significantly to ~50mb (if that) if I converted it to an MVC framework. Keep in mind, this is without user generated content like PDF, MP3, etc.
If that seems scary, I highly suggest using Joomla!, Drupal, Wordpress, or any of the other CMS systems out there. Trust me, you'll save a ton of time.
The best advice I could give you: use Wordpress, don't rebuild it yourself. It's really perfect for this job.
Bottom line: 15% of the best websites run using Wordpress.
When you start considering security, maintainability, time, and other factors - for what you are describing I would just use WordPress. Free, easy to setup and proven. It's not just making the frontend site for your viewers, you also need all the admin tools to manage it all as well.
If you do build your own, you will want to use a database to store your data. You won't create a php file for each article, you will most likely have one or few php files that focus only on loading an article page from the database using rewrite rules for nice urls. Good luck with the path you choose.
I've got a PHP application I wrote earlier that I'd like to add a RESTful API to. I'd also like to expand the site to behave more like a Rails application in terms of the URLs you call to get the items in the system.
Is there any way to call items in PHP in a Railsy way without creating all kinds of folders and index pages? How can I call information in PHP without using a GET query tag?
If you have some form of mod_rewrite going you can do this quite easily with a .htaccess file.
If you have something like this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
It will check that the file you are trying to access doesn't exist already. (Say you had a file hello.html that you still needed people to access via http://yoursite.com/hello.html)
Then if the file doesn't already exist it will load your index.php file with the rest of the URL stored in the url variable.
This means you can call something like this http://yoursite.com/pages/edit/24 and it will load index.php with /pages/edit/24 inside the url variable.
That should get you started and you won't need all kinds of folders and index pages, just mod_rewrite, .htaccess file and an index.php that will be used to load whatever you need.
You also might consider to use one of the PHP frameworks with built-in REST support, for example CakePHP.
Quick note in respopnse to Pascal MARTIN: Zend_Rest_Server has absolutely nothing to do with REST. They just do RPC with slightly nicer URLs and call it REST so that it's more trendy.
If you want to do REST, you'll need to do a bit more work yourself as I have not found a good REST library for PHP yet. So inspect $_SERVER['REQUEST_METHOD'] to decide what to do with the called resource, etcetera.
Easiest way would probably using a framework that provides you with REST-oriented functionnalities. I know Zend Framework does that, with the class Zend_Rest_Server, that allows easy creation of a REST server.
I suppose many other frameworks do just the same.
But, if you already have an application that doesn't use a framework (or that is based on a Framework that doesn't embed that kind of class), a couple of URLrEwriting rules would do just fine ; you'd just have a bit more work to map URLS/parameters to classes/methods :-(
The design pattern you are looking for is called a front controller.
In its simplest form you use mod_rewrite to pass the incoming requests and pass it to a single php script. The url is then parsed with regular expressions and mapped to different response actions. However mapping an existing application may require extensive rewriting.
If you want to play around with this concept I recommend the Silex microframework.