Archive

Posts Tagged ‘class’

JCrop Extension Implementation In PHP

March 18th, 2009 2 comments

I came across a really nice looking plugin for JQuery the other day that allowed you to select part of an image. This plugin is called JCrop.

This plugin supports things like thumbnail generation, animation, styling and event handling. The only problem is that this is all done on the client side, there is one example of a PHP script that resizes images using PHP, but this only works with JPEG images. The site says that improvements to the code are left as an exercise to the reader, so I though I would take a shot at it.

Rather than start from scratch with the PHP implementation I have adapted the ImageResize class that I talked about some months ago. I have changed the name to ImageManipulation as it has gone beyond a simple image resizing class.

I won’t post the entire source code of that class here as it will take up too much space, instead I will provide a link to it.

Talk In Code ImageManipulation class.

I’m going to be using the same JavaScript code from the Jcrop website example, but for convenience I will reproduce it here with some small changes. Basically I have removed all unnecessary HTML, included a DOCTYPE declaration, cleaned up the script tags and used the JQuery library from the Google AJAX Libraries site.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js" type="text/javascript"></script>
  <script src="jquery.Jcrop.pack.js" type="text/javascript"></script>
  <link rel="stylesheet" href="jquery.Jcrop.css" type="text/css" />
 
    <script type="text/javascript">
    //<!--
 
      $(function(){
        $('#cropbox').Jcrop({
          aspectRatio: 1,
          onSelect: updateCoords
        });
      });
 
      function updateCoords(c)
      {
        $('#x').val(c.x);
        $('#y').val(c.y);
        $('#w').val(c.w);
        $('#h').val(c.h);
      };
 
      function checkCoords()
      {
        if (parseInt($('#x').val())) return true;
        alert('Please select a crop region then press submit.');
        return false;
      };
    // -->
    </script>
  </head>
  <body>
 
    <h1>Jcrop - Crop Behavior</h1>
    <!-- This is the image we're attaching Jcrop to -->
    <img src="flowers.jpg" id="cropbox" />
 
    <!-- This is the form that our event handler fills -->
    <form action="crop.php" method="post" onsubmit="return checkCoords();">
      <input type="hidden" id="x" name="x" />
      <input type="hidden" id="y" name="y" />
      <input type="hidden" id="w" name="w" />
      <input type="hidden" id="h" name="h" />
      <input type="submit" value="Crop Image" />
    </form>
  </body>
</html>

This also includes the JCrop file (jquery.Jcrop.pack.js) and a CSS file (called jquery.Jcrop.css) that will make the selection box on the image look nice.

The function updateCoords() is used by JCrop to enter the coordinates of our crop into a set of hidden input boxes. This allows us to use a POST request to send the coordinates to our server. This is a callback function set in the JCrop initialization.

The aspectRatio setting forces the cropping box created to be square.

The checkCoords() function simply checks to see if a crop window has been created. If not then an alert is raised and the browser does nothing.

Next we need to implement our PHP code that will capture the image parameters and crop our image to a given size. This is done by creating an instance of the ImageManipulation class (giving the filename as the source), running the setCrop() method, with the correct parameters and using the show() method to display the output to screen.

<?php
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
 $src = 'flowers.jpg';
 
 require('ImageManipulation.php');
 
 $objImage = new ImageManipulation($src);
 if ( $objImage->imageok ) {
  $objImage->setCrop($_POST['x'], $_POST['y'], $_POST['w'], $_POST['h']);
  $objImage->resize(500);
  $objImage->show();
  //$objImage->save('12345.png');
 } else {
  echo 'Error!';
 }
 exit;
}
?>

This will display the output to screen only, if you want to save the output to a file then remove the comment on the line that runs the save() method.

I have put an example of this JCrop implementation in action in the same place as the ImageManipulation class. I have also created a source file so that you can download the full thing easily.

This method of cropping will work with any file type.

Paamayim Nekudotayim In PHP

January 30th, 2009 No comments

What? Don’t worry, I can’t say it either. It is officially called the Scope Resolution Operator (but also just a double colon) and is used to reference static properties and functions of a class. It is also used to reference overridden functions of classes.

To reference a constant of a class you do something similar to the following.

class MyClass {
 const CONST_VALUE = 'A constant value';
}
 
echo MyClass::CONST_VALUE;

To call a static function or a parameter you need to include the word static in the function or parameter definition. You can then reference this function through the scope resolution operator.

class MyClass {
 public static $my_static = 'static var';
 
 public static function thisIsFunction() {
 
 }
}
 
echo MyClass::$my_static; // prints 'static var'
MyClass::thisIsFunction(); // calls thisIsFunction() in MyClass

You can also use the scope resolution operator to reference functions and parameters in parent classes. This is accomplished by using the parent operator. The following code has two class definitions, one of which basically exists to call the function from the parent.

class MyClass {
 public static $my_static = 'static var';
 
 public static function thisIsFunction() {
 
 }
}
 
class ChildClass extends MyClass{
 
 public static function childFunction() {
  parent::thisIsFunction();
 }
}
 
OtherClass::childFunction(); // calls childFunction() in MyClass

The call to the childFunction() function basically calls the function thisIsFunction() in the parent class. This is useful if you want to override the parent function, but still use most of the basic functionality. For example, the child class could take in a parameter, which it then formats or alters and passes this to the parent class.

Getting Started With PHPDoc

January 26th, 2009 No comments

If you followed the tutorial on installing PHPDoc then you are probably wondering how to get started actually writing the documentation. PHPDoc will parse all the files given to it and look for comment blocks, it will then use these blocks to create the documentation for your application. A valid PHPDoc comment block must start with a '/**', have a '*' on every line and finish with '*/'. The comment must appear before the section that is being commented upon and any lines within the comment without a '*' will be ignored by the parser.

To create some sample documentation we will use the following useless class.

<?php
include('another_file.php');
 
class MyClass
{
 
  public $publicVariable = 123;
  private $privateVaraible;
 
  public function aFunciton($parameter)
  {
    // some code here...
  }
 
}

The first thing we need to do is create a file comment, this comment is intended to tell people what this file contains. In this example the file contains a single class definition and an include statement.

/**
 * MyClass File (short description about the file)
 *
 * This file contains the definition of the file MyClass (a longer description about the file).
 * @author A.N. Other
 * @version 1.0
 * @package MyPackage
 */

Notice the use of the @ symbol. This is called a tag and allows PHPDoc to assign values to internal variables. So when we use @version, we are setting the version variable for our file.

define() statements, functions, classes, class methods, and class vars, include() statements, and global variables can all be documented. So the next step is to document what the include statement includes. PHPDoc will attempt to find any files referenced through include or require statements and generate documentation for those files. If present, a link will be created from this file to that file in the documentation.

/**
 * Include the another_file.php file.
 */
include('another_file.php');

Next is our class definition, which consists of two forms of description(short and long) as well as some tags relating to things like what package the class is in.

/**
 * This is a short description about the class.
 *
 * This is a longer description which should detail exactly what the class does.
 * @package test
 * @author A.N. Other
 * @version 1.0
 * @copyright A copyright notice, if any.
 */
class MyClass
{
}

The two variables within the class must also be documented.

/**
 * A description of the variable.
 * @var integer
 */
public $publicVariable = 123;
 
/**
 * This variable will only appear in our documentation is we set the --parseprivate attribute on the command line or it has been set up in the INI file.
 * @access private
 * @var string
*/
private $privateVaraible;

Finally, we document the function. The functions are documented using the two tags of @param and @return. The @param can be defined multiple times and is a descriptive list of the parameters that the function takes. The @return value can only be defined once and describes what the function returns. If more than one datatype is returned from the function then they can be separated by a pipe (|).

/**
 * This class either returns an integer or a string.
 * @param A description about the parameter $parameter
 * @return string|int This function returns a string or an integer.
 */
public function aFunciton($parameter)
{
  // some code here...
}

To add more than one parameter just add another line in that starts with @param.

You can run PHPDoc on this file by using the following command (assuming that your project is kept in a folder called "MyProject" and that you want the documentation to go in "docs" within that directory.

C:\MyProject>phpdoc -t "C:\MyProject\docs" -o HTML:frames:default -d "C:\MyProject"

CodeSniffer File Doc Comment And Class Doc Comment

October 14th, 2008 No comments

Yesterday I wrote two posts about CodeSniffer and a common warning that I couldn’t find any decent documentation on. I thought that today I would go over something that I also had trouble finding out about, this is the file doc error. When you run CodeSniffer on a class you might find the following error being produced.

C:\php5>phpcs MyClass.php
 
FILE: MyClass.php
--------------------------------------------------------------------------------
FOUND 1 ERROR(S) AND 0 WARNING(S) AFFECTING 1 LINE(S)
--------------------------------------------------------------------------------
2 | ERROR | Missing file doc comment
--------------------------------------------------------------------------------

Most developers should be familiar with doc comments. They are used as a standard model for commenting and can also be used to generate API documentation automatically. What the CodeSniffer documentation doesn’t explain is the difference between a file doc comment and a class doc comment. A class doc comment is a comment that precedes a class, it describes not only what the class does, but also gives author, version and license information. Here is a typical (and very simple) class doc comment. The @ symbols are used to generate the API documentation.

<?php
/**
 * MyClass Class Doc Comment
 *
 * @category Class
 * @package  MyPackage
 * @author    A N Other
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://www.talkincode.com/
 *
 */
class MyClass{
}
>

A file doc comment is placed at the top of the file, above any include statements and contains pretty much the same information as the class doc comment. When added to your application your document structure might look like this.

<?php
/**
 * MyClass File Doc Comment
 *
 * @category MyClass
 * @package   MyPackage
 * @author    A N Other
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://www.talkincode.com/
 *
 */
include('anotherclass.php');
/**
 * MyClass Class Doc Comment
 *
 * @category Class
 * @package  MyClass
 * @author    A N Other
 * @license  http://www.gnu.org/copyleft/gpl.html GNU General Public License
 * @link     http://www.talkincode.com/
 *
 */
class MyClass{
}
>

As long as you make sure that different lines are spaced correctly, and that there is a single blank line between the class comment and the first parameter, you should find that running CodeSniffer will produce no errors. You will also be able to generate some pretty neat documentation which you can bundle with your application.

Categories: PHP Tags: , , , , , ,

Assign Or Get Class Name Attribute With JavaScript

May 24th, 2008 No comments

To get the class of an element with JavaScript you use the className property of the element object. Take the following section of HTML code.

<div id="adiv" class="theClass">some text</div>

Use the following bit of code to print off the class name of the div element in a message box.

alert(document.getElementById('adiv').className);

To set the class name to something else you can use the same property, but in this case just pass it a value. The following example changes the class name of the div element to "newClass".

document.getElementById('adiv').className = 'newClass';

So how is this useful? Well accessing styles can be a bit of a pain on some browsers, so a better way is to set up some styles for different classes in your style sheets and use the className property to change the class of your elements to match your styles.

For example, lets say that you wanted to create a hover effect on an element that is not an anchor. Because it isn’t an anchor there are going to be some issues with IE6 and some other browsers not understanding the pseudo-class :hover, so an alternative is to use the className property to change the class so that it has a different style.

The following example uses the onmouseover and onmouseout events to create a hover like effect.

<div id="mydiv" onmouseover="changeClass(true);" onmouseout="changeClass(false);">Content</div>
 
<script type="text/javascript">
// <!--
 
function changeClass(set){
 if(set){
  document.getElementById('mydiv').className = 'bigfont';
 }else{
  document.getElementById('mydiv').className = '';
 }
}
 
// -->
</script>

The new class is called bigfont and simply has a style that has a bigger font size. Put the following into your stylesheets.

div.bigfont{
  font-size: 123px;
  border:1px solid black;
}

Categories: JavaScript Tags: , , ,