Note to Self: Using file_exists() with Laravel 3

“path(‘www’)” seems to work, where path(‘www’) is a function that returns the relevant local file system path (/User/path_to_project/main_project_dir/www/home/images/testphoto.jpg) and not my localhost path (http://localhost/www/home/images/testphoto.jpg):

$filename = path('www') . MyUsr::find(MyAccnt::id())->user_image();
		echo '<p> vardump of filename: ';
		var_dump($filename);

		echo '<p> vardump of file_exists with filename: '; 
		var_dump(file_exists($filename));

MyUsr and MyAccnt are Laravel models. You can also swap in

var_dump( File::exists($filename) );

for

var_dump(file_exists($filename));

Using a relative path or $_SERVER[‘DOCUMENT_ROOT’] didn’t work for me, the var_dump would always return “bool(false)”.

Deleting Application Cache in Code Igniter with PHP

The Code Igniter documentation says:

Deleting Caches

If you no longer wish to cache a file you can remove the caching tag and it will no longer be refreshed when it expires. Note: Removing the tag will not delete the cache immediately. It will have to expire normally. If you need to remove it earlier you will need to manually delete it from your cache folder.

The CI_Output class ($this->output->cache(30)) doesn’t provide any public delete_cache() method. To delete database cache, you can use Code Igniter’s built in methods like $this->db->cache_delete_all(). For application cache, you need to write the code yourself.

Why would you want to?

There’re several use cases. For example, if a non-coder has just made a content update to your site via a CMS and you want to make sure it shows up immediately and not after the remaining amount of time specified via $this->output->cache(YOUR_TIME_INTERVAL).

Code snippet

Here’s one quick way to programmatically delete application cache in Code Igniter 2.1.3:

		if ($handle = opendir('YOUR_PATH_TO-application/cache')) {
		    //echo "Directory handle: $handle <br /><br/>";

		    while (false !== ($entry = readdir($handle))) 
		    {		        
		        //echo $entry."<br />";
		    	$n = basename($entry);
		    	//echo "name = ".$n."<br />";  
				//echo "length of name = ".strlen($n)."<br />";
				if( strlen($n) >= 32 ){
					//echo "file name's 32 chars long <br />";
					$p = APPPATH.'cache/'.$entry;
					//echo $p;					
					unlink($p);	
				}
				//echo "<br />";
		    }
		    closedir($handle);
		}    

Note: the //echo statements are just there for quick debugging, they shouldn’t be there in a real application.

Since Code Igniter’s application/cache directory contains only a few types of files and all of the non-cache files are named something like index.html or .htaccess, this quick approach looks for files whose names consist of 32 characters. The number is 32 because Code Igniter names cached content files using MD5 encryption.

This could potentially be slower than other ways of doing the same thing, since it involves a string manipulation method. I’m always interested in suggestions.

Using the Factory Method Pattern in PHP 5, a Quick Example

Place your factory classes & interface inside a directory of your choice, like /api/YOUR-PATH-TO-CLASSES-HERE/. Just make sure to specify that path in the __autoload() method when you use the factory (see the last code example below).

Set up the Interface

<?
interface IApiGrabr
{
	public function callApi();
}
?>

Implement the Interface with a Twitter Class

This code assumes there’s a directory named ‘api’ at your server’s public root folder. Also, note, in a live example you might want to have a separate file to store some of your Twitter, etc credentials. The Twitter oAuth library I’m using can be found on github.

<?
class TwitterApiGrabr implements IApiGrabr 
{
	public function callApi(){

		require_once('/api/twitteroauth.php'); //open source class from github

		$connection = new TwitterOAuth('your-consumer-key', 
		                               'your-consumer-secret', 
		                               'your-access-token-here',
		                               'your-access-token-secret-here');

		$content = $connection->get('account/rate_limit_status');
		
		// you can now call all the methods on the twitteroauth/connection object
		$user = $connection->get('account/verify_credentials');

		$favs = $connection->get('favorites',  array(
			  'screen_name'      => 'TechCrunch',
			  'count'            => 11,
		));

		//this is FPO, in real life write some formatted display code:
                var_dump($favs);
	}
}
?>

Implement the Interface with an Instagram Class

The below code uses a handy open source Instagram oAuth class from github.

<?
class InstagramApiGrabr implements IApiGrabr 
{
	public function callApi(){

		//open source class from github
		require_once('/api/Instagram.php'); 

		$instagram = new Instagram('your-client-id-here', 'your-client-secret-here', 'your-access-token-here');
		
		//simplified call, in real life, there should be an authentication check (see Instagram.php example on github)		  
	    try {
	        $instafeed = $instagram->get('users/self/media/liked'); 
	    }catch(InstagramApiError $e) {
	        die($e->getMessage());
	    }
		
	    //FPO JSON display, in real life, you'd format this w/ HTML, probably via a for loop	
        echo '<p>&nbsp;</p>'.json_encode($instafeed);
	}
}
?>

Implement the Interface with a Tumblr Class

<?
class TumblrApiGrabr implements IApiGrabr 
{
	public function callApi(){
		//posts
		$pth2 = 'http://api.tumblr.com/v2/blog/YOUR-TUMBLR-NAME-HERE.tumblr.com/posts/photo?api_key=YOUR-API-KEY-HERE';	

		///Tumblr account's posts - http://www.tumblr.com/docs/en/api/v2#posts
		$pthresult2 = file_get_contents($pth2);
		
		//FPO to just display raw JSON response, in real life, you'd format it with HTML
		echo $pthresult2;	
	}
}
?>

Set up your Factory class

<?
class MyFactory
{ 
  private static $dictionary;

  public static function init()
    {
      self::$dictionary = array('instagram' => new InstagramApiGrabr(), 
                         'twitter' => new TwitterApiGrabr(), 
                         'tumblr' => new TumblrApiGrabr());
    }

    public static function GetApi($param='instagram')
    {
        return self::$dictionary[$param]; 
    } 
}
?>

Use Your Factory Class Like So

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>API Test</title>
</head>
<body>
<?
  //allow PHP to auto include your individual class files as needed 
  function __autoload($class_name) {
      require_once('/api/YOUR-PATH-TO-CLASSES-HERE/'.$class_name . '.php');
  }
  
  MyFactory::init();

  /// control the below factory method calls via drop down menu, page navigation inside a carousel, etc. 

  //will spit out the Instagram JSON feed
  $a = MyFactory::GetApi('instagram');
  $a->callApi(); 

  //will spit out the Twitter JSON feed
  $a = MyFactory::GetApi('twitter');
  $a->callApi();

  //will spit out the Tumblr JSON feed
  $a = MyFactory::GetApi('tumblr');
  $a->callApi();
?>
</body>
</html>

Side Note on the Code Igniter framework and PHP interfaces

The Code Igniter mvc framework for PHP doesn’t seem to support “interface” or “implements” key words as of version 2.1.3.

PHP directory browsing/image display utility, Part 2

This is Part 2 of an earlier tutorial by the same name, “Part 1.”

I wrote this PHP5 utility as a quick and easy way to present design mockups to a reviewing party. It needed to be short and simple enough for a Designer to understand (and not freak out) and copy/paste. This script will read through a directory, either a default one, or one passed to the page via query string. It automatically reads every file in the given directory and displays the images found there. The Designer can name the files anything they want and they don’t have to edit any XML files.

This script will read through a directory, either a default one, or one passed to the page via query string. It automatically reads every file in the given directory and displays the images found there. The Designer can name the files anything they want and they don’t have to edit any XML files.

I chose to store the FolderBrowser class in a directory called com/timshaya/utils/, using the standard domain-based format. Here’s the code for FolderBrowser.php:

<?php		

	class FolderBrowser 
	{	
		private $myarr = array();
	
	    public function getArr() { return $this->myarr; }	
	
		public function __construct($vers)
		{ 
			($vers == null) ? $vers = "images" : $vers = $vers;

			$myDir = opendir($vers);		
			while (false !== ($file = readdir($myDir)))
			{
				if($file != "." && $file != ".." && $file != ".DS_Store")
				{
					array_push($this->myarr, $file); 	
				}
			}
			closedir($myDir);				
			
			$this->spitOutImgs($vers);
    	}
		
		public function spitOutImgs($vers)
		{			
			$ar = $this->getArr();
			for($i = 0; $i < count($ar); $i++)
			{	
				$pth = $vers."/".$ar[$i];
				$s = getimagesize($pth);						
				$c2 = "<div class='dv1'><img src='".$vers."/".$ar[$i];
				$c2 .= "' /><br />".$s[0]."x".$s[1]."</div>";	
				echo $c2; 	
			}
		}	
	}

?>

You can use the above class like so:

<?php 
    $version = htmlspecialchars($_GET["version"]); 
	require("com/timshaya/utils/FolderBrowser.php");
?>

<!-- <DOCTYPE... <html>...<body>... -->

<?php $myFolder = new FolderBrowser($version);	  ?>

<!-- ... </html>  -->

When I have some free time, I’ll continue this in Part 3. The next step would be to redesign FolderBrowser in such a way that it accounts for sub directories inside the main directory ($vers). I’ll probably create an interface or abstract class called AbstractFolderBrowser with basic functionality or method signatures. Then separate the logic currently in __construct() into a processDir() method. Each subclass of AbstractFolderBrowser will most likely override the processDir() method. So, SimpleFolderBrowser will do what’s above, with a few small changes, while SubDirFolderBrowser will be a bit more complex and accommodate sub directories, etc.

PHP5 directory browsing/image display utility, Part 1

I wrote this PHP5 utility as a quick and easy way to present design mockups to a reviewing party. It needed to be short and simple enough for a Designer to understand (and not freak out) and copy/paste.

This script will read through a directory, either a default one, or one passed to the page via query string. It automatically reads every file in the given directory and displays the images found there. The Designer can name the files anything they want and they don’t have to edit any XML files. This code can also be used to spit data out to either HTML or Flash.

<?php $version = htmlspecialchars($_GET["version"]); ?>

<!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">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <title>creative presentation</title>
    <link rel="stylesheet" href="css/common.css" type="text/css">		
</head>
<body>

<div id="container">
<h1> Here're the images</h1>

<?php		

	$contnt1 = "";
	$contnt2 = "";
	$myArr = array();	
	
	if($version == null) 			 
		$version = "images"; 
	
	$myDir = opendir($version);		
	while (false !== ($file = readdir($myDir)))
    {
		if($file != "." && $file != ".." && $file != ".DS_Store")
		{				
			//$contnt1 = "file name = ".$file."<br />";
			//echo $contnt1."<br><br>";
			array_push($myArr, $file);
		}
	}
	closedir($myDir);	
	
    $contnt2 = spitOutImgs("html", $version, $myArr);	
	echo $contnt2;	

	function spitOutImgs($whichFrontEnd, $version, $arr)
	{
		for($i = 0; $i < count($arr); $i++)
		{	
			$pth = $version."/".$arr[$i];
			$s = getimagesize($pth);
			if($whichFrontEnd == "html"){				
				$c2 = "<div class='dv1'><img src='".$version."/".$arr[$i]."' /><br />".$s[0]."x".$s[1]."</div>";	
			} else if($whichFrontEnd == "flash") {
			    $c2 = $version."/".$arr[$i];
			}	
			echo $c2; 		
		}
	}		
	
?>

</div>
</body>
</html>

In Part 2, I rewrite the above code as a Class file.