Comm Lab Web Week 3

PHP Functions and Objects

Functions

<?PHP
	
	function myFunction($somearg)
	{
		// You would do something here
		return "You passed in $somearg";
	}
	
	$passing_in = "Hello World";
	$return_value = myFunction($passing_in);
	echo($return_value);
	
	echo("\n");
?>
		
More Information:
  • PHP: Functions - Manual
  • Classes and Objects

    <?PHP
    	class MyClass
    	{
    		var $myClassVar;
    
    		function set_var($new_var)
    		{
    				$this->myClassVar = $new_var;
    		}
    
    		function get_var()
    		{
    				return $this->myClassVar;
    		}
    	}
    
    	$aClass = new MyClass;
    	$aClass->set_var("something");
    	echo("Var: " . $aClass->get_var() . "\n");		
    ?>
    		

    Classes and Objects in PHP are very similar to Java/Processing. Syntactically though they don't use the "." operator, instead using "->". Also, in the class definition you need to use the "this" keyword.

    More Information:
  • PHP: Classes and Objects - Manual
  • Data Storage

    As you might have discovered, storing and retrieving data is often a big part of web development. Typically a database is employed to store the data in an organized fashion.

    One of the primary types of databases is a relational database such as Oracle or MySQL. A simplified view of a relational database is a series of linked spreadsheets.

    DataMapper - ORM

    ORM is object relational mapping. Meaning we can construct objects in code and store them in a relational database.

    phpDataMapper is one such ORM that works with PHP and MySQL.

    To use it, download phpDataMapper.zip file from our class site and upload the entire unzipped folder to the directory where you will be placing your PHP scripts on the server.

    Here is how you setup a script to use it. In this case the data model is for comments:

    <?
    // Require the code
    require 'phpDataMapper/Base.php';
    
    // Setup the datamodel that we'll use to structure out data
    class DataModel extends phpDataMapper_Base
    {
    	//http://phpdatamapper.com/documentation/column-types/
        
        // Specify the data source (table for SQL adapters)
        protected $_datasource = "comments";
     
        // Define your fields as public class properties
        public $id = array('type' => 'int', 'primary' => true, 'serial' => true);
        public $user = array('type' => 'string', 'required' => true);
        public $message = array('type' => 'text', 'required' => true);
        public $date_created = array('type' => 'datetime');
    }
    
    // Setup the adapter to the database
    $databaseAdapter = new phpDataMapper_Adapter_Mysql('database hostname', 'database name', 'database user', 'password');
    // Create the model
    $dataMapper = new DataModel($databaseAdapter);
    // Create the tables if needed
    $dataMapper->migrate();
    ?>		
    		

    To put a comment into the database you would do the following:

    // Create an empty object
    $comment = $dataMapper->get();
    // Fill it in
    $comment->message = "Some Message Text";
    $comment->user = "Shawn";
    // Save it in the database
    $dataMapper->save($comment);
    		

    To get and display all of the comments, you would do the following:

    // Get all of the comments
    $comments = $dataMapper->all();
    foreach ($comments as $comment) {
    	print($comment->user . " " . $comment->message . "
    "); }

    To only get comments who have the "user" of "Shawn", you would do this (the => operator assigns a value to a key, in this case, assigning "Shawn" to "user"):

    // Get all of Shawn's comments 
    $shawns = $dataMapper->all(array('user' => 'Shawn'));
    foreach ($shawns as $shawn) {
    	print($shawn->user . " " . $shawn->message . "
    "); }

    A full comment system example:

    <?
    // Require the code
    require 'phpDataMapper/Base.php';
    
    // Setup the datamodel that we'll use to structure out data
    class DataModel extends phpDataMapper_Base
    {
    	//http://phpdatamapper.com/documentation/column-types/
        
        // Specify the data source (table for SQL adapters)
        protected $_datasource = "comments";
     
        // Define your fields as public class properties
        public $id = array('type' => 'int', 'primary' => true, 'serial' => true);
        public $user = array('type' => 'string', 'required' => true);
        public $message = array('type' => 'text', 'required' => true);
        public $date_created = array('type' => 'datetime');
    }
    
    // Setup the adapter to the database
    $databaseAdapter = new phpDataMapper_Adapter_Mysql('database hostname', 'database name', 'database user', 'password');
    // Create the model
    $dataMapper = new DataModel($databaseAdapter);
    // Create the tables if needed
    $dataMapper->migrate();
    
    //////////
    // Add a new comment if they submitted the form
    /////////
    
    if (isset($_GET['name']) && isset($_GET['comment'])) {
    	// Create an empty object
    	$comment = $dataMapper->get();
    	// Fill it in
    	$comment->message = $_GET['comment'];
    	$comment->user = $_GET['name'];
    	// Save it in the database
    	$dataMapper->save($comment);
    }
    
    ////////////
    // Get all of the existing comments
    ///////////
    
    $comments = $dataMapper->all();
    
    
    ?>
    <html>
    	<head>
    		<title>Comments</title>
    	</head>
    	<body>
    		<div>
    			<form name="myform" method="GET" action="index.php">
    				Name: <input type="text" name="name" /><br />
    				Comment: <textarea name="comment" cols="50" rows="10"></textarea><br />
    				<input type="submit" name="submit" value="Submit Comment" />
    			</form>
    		</div>
    		
    		<div>
    <?
    foreach ($comments as $comment) {
    	print($comment->user . " " . $comment->message . "<br />");
    }
    ?>
    		</div>
    	<body>
    </html> 		
     		

    You can also use SQL to create custom queries. Here is a quick example:

    // Custom Query
    $lesscomments = $dataMapper->query("select * from comments where user = 'Shawn'");
    foreach ($lesscomments as $lcomment) {
            print_r($lcomment->message);
    }
    

    Of course, if you needed to change or update records you could do that as well. To do an update, you need an individual record or row and then you modify the data and call update:

    // Select all
    $comments = $dataMapper->all();
    
    foreach ($comments as $comment) {
    	// Change the data
        $comment->message="blah blah";
    	
    	// Call update
        $dataMapper->update($comment);
    }
    

    There is more documentation on phpDataMapper available: Getting Started and Types

    phpMyAdmin is a great tool for examining our data in MySQL

    Command Line

    Learn Enough Unix for your Resume