PHP Classes
PHP Classes
elePHPant
Icontem

Using Microsoft Visual Studio as PHP IDE with the PHP Tools extension: Part 2 Developing a CRUD application with a noSQL database

Recommend this page to a friend!
  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog Using Microsoft Visua...   Post a comment Post a comment   See comments See comments (0)   Trackbacks (0)  

Author:

Posted on:

Categories: PHP Tutorials, Sponsored

There are many IDEs for PHP development. All of them provide common features but when we get closer we notice that there are some that provide different features that make them better for our purposes.

Thanks to the PHP Tools extension it is possible to use Microsoft Visual Studio for PHP development and benefit from some of Visual Studio features for this purpose.

Read this tutorial article to learn about the way it works for developing a practical PHP application, in this case a CRUD application based on a noSQL JSON file database.




Contents

Introduction

Your first project

Working with files

Completing the project code

Running the project

Conclusion

Project Code


Introduction

In the first article of this article we discussed the advantages of using an Integrated Development Environment (IDE) and how to install and setup the PHP Tools extension for use with Microsoft's Visual Studio. In this article we will use the IDE to develop a practical example of CRUD operations interface on a noSQL JSON Database.

While the code used here is operational, it is not production ready and should be considered an exercise in learning how to use the PHP Tools.

For your convenience, the complete code will be available at the end of the article which will allow you to cut and paste it into your project or you may download from here. However you should follow along with the presented examples to get a feel for using the IDE.

Your first project

Visual Studio uses 'Solutions' which contain one or more 'Projects'. After starting Visual Studio, select File-> New-> Project (Ctrl+Shift+N) to display the 'New Project' dialog.

new project

From the template options on the left, select Installed-> Templates-> PHP, and you should be presented with the project templates. We will be creating a PHP Web Project, so select that template.

1. Name your project 'jsondb'.
2. Change the Location if you want to store your files somewhere else than the default.
3. Ensure the options to 'Create directory for solution' and 'Add to Source Control' are not checked.
4. Select OK and the project will be created.

Note that there are other project templates available to choose from. You can select them and read a brief description of what type of projects they are designed for.

If you have the 'Keep directory for solution' option checked, a folder will be created for the solution and another folder off of that for this project, which will allow multiple projects in the same solution. In this example, we only have the one project.

Working with files

Notice that the project template has already created our first file for us, the index.php file. We are going to be doing more that just outputting 'Hello World', so highlight that line and delete it.

Add the following line and as you start typing notice that the code completion feature will display a list of possible choices. You can keep typing until require_once is selected or select it yourself at any time. When you press enter, the selection will be added to your code for you, which you can then complete.

<?php
require_once('jsondb.init.php');
?>

As you can tell, we are including a file named jsondb.init.php which we have not created yet, so we will create that now.

In the Solution Explorer section, right click on the project name 'jsondb' and select Add-> New Item (Ctrl+Shift+A) from the popup menu to display the 'Add New Item' dialog.

new file

1. Select 'PHP Script' from the list of file templates.
2. Name it jsondb.init.php.
3. Select 'Add' to create the new PHP file and add it to the project.

This will be the initialization file for our project so add the following code to it...

<?php
require_once('jsondb.class.php');
$jdb = new jsondb;
?>

Note that this is a bit of overkill for our simple project, however it demonstrates including multiple files in a chain. In this case we are including another file named jsondb.class.php and instantiating the class which will be in it.

We need to create this file so, once again, right click on the project name 'jsondb' and select Add-> New Item (Ctrl+Shift+A) from the popup menu to display the 'Add New Item' dialog.

1. Select 'Class' from the list of file templates.
2. Name it jsondb.class.php.
3. Select 'Add' to create the new PHP class file and add it to the project.

Using the Class file template has generated the start of our class code for us with a comment section including PHP Doc keywords for the version and author. This comment section has the code folding feature attached to it, so you can expand and collapse it by pressing the +/- signs.

Change the code to look like this...

<?php
/**
* CRUD operations on a JSON noSQL database.
*
* Main class for creating, retrieving, updating and deleting records in a JSON noSQL database.
*
* @version 1.0
* @author Dave
*/
class jsondb
{
public $dataFolder = 'jsondata';
}
?>

Currently all our class does is define the $dataFolder property, which will be the folder where our JSON Database files will be stored.

To create this folder, right click the project name 'jsondb' and select Add-> New Folder from the popup menu. You will see the new folder added to the project, name it 'jsondata' and enter to save your changes.

Completing the project code

At this time, you can refer to the complete class code located at the end of this article and start entering the methods. When you feel comfortable with using the IDE and its automatic indent and code completion features, go ahead and just copy and paste the entire code into your jsondb.class.php file.

If you place your cursor anywhere in the property text $dataFolder, you will notice that all references to it in the methods will be highlighted. If you rename this property, there will be a small underline box that you can hover over and choose to automatically update all the references to it throughout your project.

Use the complete code located at the end of this article for the index.php file to also finish it.

Notice the first line to reference our class, $dbData = $jdb->rDataBase($dbName);. If you right click on the method text 'rDataBase' and select 'Go To Definition' (F12) from the popup menu, you will be taken to the class file and the rDataBase definition.

Running the project

toolbar

Make sure all your changes have been saved and that index.php is the active file. You can now select and click on the browser you want to test in from the toolbar.

If PHP and xDebug have not been set up yet, you will see the dialog to set up your server. We will be using the built in server which should already be selected for you and with one click you can continue and the IDE will install and configure everything you need to run your code locally. You will only need to do this once, or if you decide to configure the IDE to your own local web server.

If all went well, you should now be running the script in your browser on the localhost. Feel free to play around and test the project, however keep in mind that this not a production ready project so take it easy on the amount of data stored and navigating back with the browser history.

You can go back to the code in the IDE and make any changes you want. Notice that the toolbar will indicate that the script is running, so you just need to refresh the page in your browser to see those changes.

Conclusion

This second part of the series was intended to give you an overview of using the PHP Tools with a practical code example. The more you explore and use the IDE, the more proficient you will become and the sooner you will realize the full benefits of coding with a powerful set of professional tools behind you.

In the third, and final, installment we will look into the powerful debugging features of PHP Tools and the Visual Studio IDE.

If you liked this article, please share it with other developers that would like to know how create PHP projects with Microsoft Visual Studio benefiting from the integration with PHP provided by the PHP Tools extension.

Project Code

index.php

<?php
require_once('jsondb.init.php');
if ($_REQUEST['process'] and $_REQUEST['dbName']) {
$dbName = $_REQUEST['dbName'];
$dbData = $jdb->rDataBase($dbName);
switch ($_REQUEST['action']) {
case 'createDB':
$jdb->cDataBase($dbName);
break;
case 'updateDB':
if (empty($_REQUEST['id'])) {
//adding record
$id = $jdb->nextRecord($dbData);
$dbData[$id]['title'] = (!empty($_REQUEST['title'])) ? $_REQUEST['title'] : $dbData[$id]['title'];
$dbData[$id]['author'] = (!empty($_REQUEST['author'])) ? $_REQUEST['author'] : $dbData[$id]['author'];
} else {
$id = $_REQUEST['id'];
if (empty($_REQUEST['title']) and empty($_REQUEST['author'])) {
//removing record
foreach ($dbData as $key => $value) {
if ($key == $id) {
continue;
}
foreach ($dbData[$key] as $field => $value) {
$dbNew[$key][$field] = $value;
}
}
$dbData = $dbNew;
} else {
//changing record
$dbData[$id]['title'] = (!empty($_REQUEST['title'])) ? $_REQUEST['title'] : $dbData[$id]['title'];
$dbData[$id]['author'] = (!empty($_REQUEST['author'])) ? $_REQUEST['author'] : $dbData[$id]['author'];
}
}
$jdb->uDataBase($dbName, $dbData);
break;
case 'deleteDB':
$jdb->dDataBase($dbName);
unset($dbData);
break;
}
} else {
$dbName = 'test.jdb';
$dbData = $jdb->rDataBase($dbName);
}
?>
<!DOCTYPE HTML>
<html>
<head>
<title>jsonDB Test Script</title>
</head>
<body>
<form method="post">
Database Name: <input type="text" name="dbName" value="<?php
echo HtmlSpecialChars($dbName);
?>" /><br />
<input type="radio" name="action" value="createDB" /> Create<br />
<input type="radio" name="action" value="deleteDB" /> Delete
<hr />
Record ID: <input type="text" name="id" /> <em>(Leave blank to use next ID number)</em><br />
Title: <input type="text" name="title" /><br />
Author: <input type="text" name="author" /><br />
<input type="radio" name="action" value="updateDB" /> Update<br />
<em>(Providing a record id without a title or author will delete that record)</em>
<hr />
<input type="hidden" name="process" value="1" />
<input type="submit" name="formSubmit" value="Submit" />
</form>
<hr />
<?php
var_dump($dbData);
?>
</body>
</html>

jsondb.class.php

<?php
/**
* CRUD operations on a JSON noSQL database.
*
* Main class for creating, retreiving, updating and deleting records in a JSON noSQL database.
*
* @version 1.0
* @author Dave
*/
class jsondb
{
public $dataFolder = 'jsondata';
/**
* Creates database file
*
* @param string $dbName Name of database file to create
* @return void
*/
public function cDataBase($dbName){
$fileName = $this->dataFolder.'/'.$dbName;
file_put_contents($fileName,null,FILE_APPEND);
}
/**
* Retrieves database data
*
* @param string $dbName Name of database file to retrieve
* @return array Data or empty if none
*/
public function rDataBase($dbName){

$fileName = $this->dataFolder.'/'.$dbName;
$dataString = file_get_contents($fileName);
$data = json_decode($dataString,true);
if( is_array($data) ){
ksort($data);
return $data;
}else{
return array();
}
}
/**
* Updates database data
*
* @param string $dbName Name of database file to update
* @param array $data Data to update
* @return void
*/
public function uDataBase($dbName,$data){
$fileName = $this->dataFolder.'/'.$dbName;
$jsonData = json_encode($data);
file_put_contents($fileName,$jsonData);
}
/**
* Deletes database
*
* @param string $dbName Name of database file to delete
* @return void
*/
public function dDataBase($dbName){
$fileName = $this->dataFolder.'/'.$dbName;
unlink($fileName);
}
/**
* Gets next record id
*
* @param array $data Database data
* @return int Id of next record
*/
public function nextRecord($data){

if( is_array($data) ){
ksort($data);
end($data);
$id = key($data)+1;
}else{
$id = 1;
}
return $id;
}
}
?>



You need to be a registered user or login to post a comment

1,512,413 PHP developers registered to the PHP Classes site.
Be One of Us!

Login Immediately with your account on:

FacebookGmail
HotmailStackOverflow
GitHubYahoo


Comments:

No comments were submitted yet.



  Blog PHP Classes blog   RSS 1.0 feed RSS 2.0 feed   Blog Using Microsoft Visua...   Post a comment Post a comment   See comments See comments (0)   Trackbacks (0)