PostgreSQL & PHP Tutorials - Using Your API
PHP »
Introduction to Object Oriented Programming
Viewing page 5 of 5
« |
Back | Next | »
How do we use this new api?
Here's how we create an item (assuming you have created a form to post this information):
<?php
// this also includes the parent api - we don't need to worry about it.
require('news_api.php');
$news_api = new News_API();
$news_title = $_POST['news_title'];
$news_description = $_POST['news_description'];
$news_api->Set('title', $news_title);
$news_api->Set('description', $news_description);
$created_ok = $news_api->Create();
if ($created_ok) {
echo "News item created!<br/>";
} else {
echo "News item not created<br/>";
}
?>
Here's how we fetch and display a news item:
<?php
// this also includes the parent api - we don't need to worry about it.
require('news_api.php');
// get which news item to display from the URL and make sure it's an integer (this will stop database errors).
$newsid = (int)$_GET['newsid'];
$news_api = new News_API();
$loaded_ok = $news_api->Load($newsid);
if (!$loaded_ok) {
echo "News item " . $newsid . " doesn't exist<br/>";
exit();
}
$news_title = $news_api->Get('title');
$news_description = $news_api->Get('description');
echo 'News title: ' . $news_title . '<br/>';
echo 'News description: ' . $news_description . '<br/>';
?>
Easy!
The advantages of doing it this way are numerous.
We could do this using functions, with a separate file for each type you want to use (eg news, blogs, articles and so on). The problem with that comes when you want to include multiple types on the same page - you can't have multiple functions with the same name. This problem doesn't exist using classes because each class is treated separately with different 'methods' (even though the code itself to 'load' or 'save' an item could be exactly the same).
Another developer could use exactly the same functions to put this content on another part of their site. They don't need to know the database structure or what queries you have to run, they just include the API and call the methods you allow. Commenting your code using phpdocs style comments (as you can see them here) will help immensely.
The last (and maybe the best!) reason is you only have one place to look for bugs. If you use an API for a cms, you'll use the same functions whether you're in the admin area (where you add or edit your content) and in the 'frontend' or public area that everyone gets to see. If you come across a bug (eg you're not properly escaping input or output), you only need to look in one place to check it!
Viewing page 5 of 5
« |
Back | Next | »
Avg Rating: 4
Vote Count: 10
