CodeIgniter – Bonfire Series – Database Migration Systems

February 20th, 2012 | by | bonfire, codeigniter, php programming

Feb
20

Series – Migrations

One of my favorite parts of Bonfire is the built in Migration System, If you already understand what they are for then you can skip down
a few paragraphs and I’ll show you how to make them. For those who don’t know what a Migration system is, it basicly like version control for
your database schemes. Let’s say you created a Media Module and when you created it, a few weeks go by and you decided to add another
Database Table or even a Index Key. Well that’s the best part of the Migration system, All you have to do is Create a new Migration controller, stick
it in your module/migrations folder and now you can add to your database or remove from it, Sure beats trying to remember what
you changed on a Module you built a year ago and upgraded 3 or 4 times. Anyway on to how to properly make one.

File Name and Controller Name

The syntax for naming your files and controllers is 000_install_modulename_whatever.
Now the numerics at the start should go higher then the last one, so if you have a 001_install then you need to make it 002
Let’s start with one I created last night, since I used to Module Builder using a pre-made Table, so the Module Builder
Created my permissions for me, but didn’t create a SQL table incase I want to reuse this module at a later date. So let’s go ahead and make a Migration to add
and delete the SQL Table.

 
	<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
 
	// Class and file name must match or you will kill a kitten and a evil unicorn will rob you
	// Ok Now the Filename for this file is 002_Install_media_tables.php
	// The Controller name, I just personally remember to remove the numbers and add Migration in front of the file name.
 
 
	class Migration_Install_media_tables extends Migration {
 
		/*
			method: up()
 
			This method is run everytime you upgrade your migration, it handles the actual database creation. 
 
		*/
		public function up() 
		{
			//Set the Database Prefix
 
			$prefix = $this->db->dbprefix;
 
			//You can use SQL or dbforge,  I personally prefer the dbforge, it's well documented in the CodeIgniter User Guide.
 
			//Since where creating a table, very simple let's setup the fields to add
			$this->dbforge->add_field('`id` int(11) NOT NULL AUTO_INCREMENT');
			$this->dbforge->add_field("`media_cat` int(11) NOT NULL");
			$this->dbforge->add_field("`filename` VARCHAR(200) NOT NULL");
			//Let's set the primary key, since the second parameter is set to true this will become a primary key 
			$this->dbforge->add_key('id', true);
			//Let's set the secondary key, since this table has a N to Many relation ship, I added a key for the media category. 
			$this->dbforge->add_key('media_cat');
 
			//And now that we have the table all ready to go, let's create it.  Tell me that wasn't faster then trying to figure it out with PhpMyAdmin or something.
			$this->dbforge->create_table('media_files');
 
		}
 
		//--------------------------------------------------------------------
 
		/*
			method : down();
 
			Performs a quick drop table on the actual table
		*/
		public function down() 
		{
			$prefix = $this->db->dbprefix;
			$this->dbforge->drop_table('media_files');
		}
 
		//--------------------------------------------------------------------
 
	}		
	?>

Well I hope this helps someone with creating Migrations on there own

Bonfire’s Awesome Module Builder is just a quick kick-start to building your , learning the Migrations and how to add/remove DB Fields with your
migrations will make your modules more scalable, flexable, and if you only have to build the module one time, Then your building Assets that the next time
you need one, you can just pop it in place and be done with it. The re-usability of the HMVC modules with CodeIgniter is execellent and Bonfire has made it
even better.
If you have any questions or ideas for guides that you would like to see post a comment, send me a message, or catch me on twitter.

Tags: , , ,

No Comments »

CodeIgniter – Bonfire Series – Template Blocks

February 17th, 2012 | by | bonfire, codeigniter, php programming

Feb
17

Series – Using Template Blocks

This is a basic guide to using the Template Block methods, in Bonfire’s Template class, you have Block’s which I personally use for things
like Sidebar Navigation, Module on Certain Pages, etc, etc. There’s been a little confusion on the proper usage of these so I figured I’d write a quick short guide on how I personally use them in my workflow.

Step 1 – Setting the Block in your Theme

Ok Template Blocks, are like view partial’s that can be changed inside of your Controller Method’s, the best part of Block’s is that you can set a default Block view file, or just set a spot for the block to and leave the default empty so they only appear when needed.

In this guide we will be using the default Template directory, and the HomeController so these files are located on a default Bonfire installation at

  • /bonfire/themes/default/index. <- Main Template Files
  • /bonfire/application/controllers/home.php <- Default Home Controller

Let’s start with creating 2 files. block1.php and block2.php Both of these files will go in your template directory which is /bonfire/themes/default/

Let’s Start with the Home Controller

	<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
 
	class Home extends Front_Controller {
 
  //--------------------------------------------------------------------
 
  public function __construct() 
  {
		parent::__construct();
  }
 
	//--------------------------------------------------------------------
 
	/*
	    method : index()
 
	    Simple Index Method to show Template Block 1
	*/
	public function index()
	{                        
		//Set Block named "newblock" to use view "block1"
		Template::set_block('newblock', 'block1');
		Template::render();
	}
 
	//--------------------------------------------------------------------
 
	/*
	    method : index()
 
	    Simple Index Method to show Template Block 1
	*/
	public function block2()
	{                        
		//Set Block named "newblock" to use view "block2"
		Template::set_block('newblock', 'block2');
		Template::render();
	}
 
	//--------------------------------------------------------------------
 
}
/* End file bonfire/applications/controllers/home.php */
?>

Ok that’s the main default home front-end controller, We have 2 method’s inside of it to change Block’s, now inside of your Template Index file which is located at /bonfire/themes/default/index.php, Lets just add a setting to create a space for these blocks, I am using the Default Template File which I just pulled from Github.

 
<?php
	// Setup our default assets to load.
	Assets::add_js( array(
		base_url() .'assets/js/jquery-1.7.1.min.js',
	));
?>
<!doctype html>
<html lang="en">
<head>
	<meta charset="UTF-8" />
 
	<title><?php echo config_item('site.title'); ?></title>
 
	<link rel="shortcut icon" type="image/x-icon" href="/favicon.ico">
 
	<?php echo Assets::css(); ?>
 
	<?php echo Assets::external_js('head.min.js'); ?>
</head>
<body>
 
	<div class="page">
 
		<!-- Header -->
		<div class="head text-right">
 
			<h1>Bonfire</h1>
		</div>
 
/*
	Only change I made is to add a Call for the New block here, I did not provide a default block view so only controllers that set a block view will show a block view.
*/
<?php Template::block('newblock'); ?>
		<div class="main">
			<?php
				// acessing our userdata cookie
				$cookie = unserialize($this->input->cookie($this->config->item('sess_cookie_name')));
				$logged_in = isset ($cookie['logged_in']);
				unset ($cookie);
 
				if ($logged_in) : ?>
			<div class="profile">
				<a href="<?php echo site_url();?>">Home</a> |
				<a href="<?php echo site_url('users/profile');?>">Edit Profile</a> |
				<a href="<?php echo site_url('logout');?>">Logout</a>
			</div>
			<?php endif;?>
 
			<?php echo Template::message(); ?>
			<?php echo isset($content) ? $content : Template::yield(); ?>
 
		</div>	<!-- /main -->
	</div>	<!-- /page -->
 
	<div class="foot">
		<?php if (ENVIRONMENT == 'development') :?>
			<p style="float: right; margin-right: 80px;">Page rendered in {elapsed_time} seconds, using {memory_usage}.</p>
		<?php endif; ?>
 
		<p>Powered by <a href="http://cibonfire.com" target="_blank">Bonfire <?php echo BONFIRE_VERSION ?></a></p>
	</div>
 
	<div id="debug"></div>
 
	<script>
		head.js(<?php echo Assets::external_js(null, true) ?>);
		head.js(<?php echo Assets::module_js(true) ?>);
	</script>
	<?php echo Assets::inline_js(); ?>
</body>
</html>

I know this is a simple topic, but it seems to have caused some confusion lately so i’m hoping this quick short guide will help people understand how the blocks are set and work. There usage is amazing, I personally use them for my Template head, footer, sidebar, navbar, and whatever else I need for my blocks. As always please check the bonfire doc’s for more information on there usage.

Tags: , , , ,

No Comments »

CodeIgniter – Bonfire Series – AJAX Form Submission with JSON Results

February 16th, 2012 | by | bonfire, codeigniter, jquery, php programming

Feb
16

Series – Form Posting

Returning a JSON Value and Replacing a Image SRC

Using GoogleCharts QR Code Creator Library

Since the theory behind this tuturail, is more replacing a image tag on a AJAX Forum Submit, we will be using a Library already created
You can download it at Github, I didn’t create the library but its useful, I originally found it as a Spark but installing Sparks into Bonfire is beyond the scope of this article so just download the library and stick it in your bonfire/application/librarys/ directory for now

Ok Create a Basic Module using the Module Builder, you shouldn’t need a database table for this, personally I just suggest creating a Module with a public context, if you wanna add to it later you can but the focus of this article is binding Form Submission with Creating the
URL to the New Image and Replacing the Source of the Original Image.

Ok, you have your basic Front_End Controller, Let’s take a look at mine and break it down to make sense.

	<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
 
	class qrcode extends Front_Controller {
 
	// Set some Private Variables used in this Controller
	private $g_config = array();
	private $baseurl;
 
  //--------------------------------------------------------------------
 
  public function __construct() 
  {
		parent::__construct();
 
		$this->load->library('form_validation');
		$this->form_validation->CI =& $this;
 
		//Setup Google Charts Config URL
		$this->g_config['google_charts_base_url'] = 'https://chart.googleapis.com/chart';
		//Load GR Code Library
		$this->load->library('Gc_qrcode', $this->g_config);
		//Set a Variable for a Starting QR Code to be Generated            
		$this->baseurl = 'http://blog.s-vizion.com/';
  }
 
	//--------------------------------------------------------------------
 
	/*
	    method : index()
 
	    Base Method for Non AJAX Calls and for Inital Display of the Form
	*/
	public function index()
	{                        
 
		$url = $this->baseurl;
 
		// Check if input post is submitted, if so set URL to new URL
 
		if ( $this->input->post('submit') )
		{
	    $url = $this->input->post('linkto');
		}
 
		$this->gc_qrcode->size(250)->data( $url );
 
		$img = $this->gc_qrcode->img(array('id' => 'qrimg'));
 
		// Load the Inline JavaScript to Bind the Submit Handler to Post a AJAX Call to The AJAX Method
		Assets::add_js( $this->load->view('qrjs', null, true), 'inline');
		// Set Template Variable for Image
		Template::set('img', $img );
		// Render Template
		Template::render();
	}
 
	//--------------------------------------------------------------------
 
	/*
		method : ajax_qr()
 
		AJAX Method to Return the JSON Value for the URL of the New Image Tag
		Can be Secured with a Check if IS_AJAX but I'm not gonna add that to the scope of this tut
	*/
	public function ajax_qr()
	{
    $url = $this->baseurl;
    if ( $this->input->post('linkto') )
    {
      $url = $this->input->post('linkto');
    }
    // Create New QR Code
    $this->gc_qrcode->size(250)->data( $url );
    // Get URL to New QR Code
    $img = $this->gc_qrcode->url();
    // Set Output as JSON and Output the Content as JSON array
    $this->output->set_content_type('application/json')->set_output(json_encode(array('img' => $img )));
 
    return false;
  }
 
}
/* End file bonfire/modules/makeqr/controllers/makeqr.php */
?>

Ok that’s the main front-end controller, It would be located in bonfire//makeqr/controllers/makeqr.

Now we need to create the view’s and javascript for this, I personally use Twitter’s Bootstrap V2 on my site’s so your gonna get my view’s
You should be able to easily figure out how to modify it to fit your site or if your already using Bootstrap then away you go.

Ok first, inside of modules/makeqr//index.php, let’s replace the file with this one.

 
	<section id="qrcodes">
    <div class="page-header">
      <h1>QR-Code <small> Make your own QR Code by filling out the form!</small></h1>
    </div>
 
	<?php if ( validation_errors()) : ?>
	<div class="row-fluid">
    <div class="span12">
      <div class="alert alert-error fade in">
  	    <a data-dismiss="alert" class="close">×</a>
	      <?php echo validation_errors(); ?>
      </div>
    </div>
	</div>
	<?php endif; ?>
 
	<div class="row-fluid">
	  <div class="span4">
	    <?php if ( isset ( $img ) ) echo $img; ?>    
	  </div>
 
	  <div class="span6">
		<?php echo form_open($this->uri->uri_string(), 'class="form-horizontal" id="makeqr"'); ?>
 
		<div class="control-group">
			<label class="control-label" for="linkto">Website URL : </label>
			<div class="controls">
				<input class="span6" tabindex="1" type="text" id="linkto" name="linkto" placeholder="http://shawnc.org" value="<?php echo isset($makeqr) ? $makeqr->linkto : set_value('linkto') ?>" />
			</div>
		</div>
 
		<div class="control-group">
			<label class="control-label" for="submit">&nbsp;</label>
			<div class="controls">
			<input class="btn btn-success" type="submit" name="submit" id="submit" value="Create QR-Code" />
			</div>
		</div>
 
		</form>
 
	  </div>  
	</div>

Ok so that’s the basic form for the QR Code Creation, this can be done with any library or any form, I’m just using something I already made for a personal site, just remember the ideas and theory’s behind this are not restricted to this one application.
So all that’s left now is to include the actual JS file that makes the magic happen. One thing You’ll need to find a Loading Image for the
AJAX image loading, there’s ton’s of placing to get them at, I personally just used the same one I use on my lightboxes.

Anyway the last piece needed is the javascript, which we loaded as a view since I wanted to include some PHP in it, Here it is

 
			 //Form ID is set to "makeqr"
			 //The URL Value is IDed as "linkto"
			 //The Image to Replace is IDed as "qrimg"
 
       $("#makeqr").submit(function()
       {
         var dataString = $("#linkto").val();
         var img_rep    = $("#qrimg");
         img_rep.attr('src', '<?php echo base_url(); ?>assets/images/loading.gif');
        $.post(  
            "<?php echo base_url(); ?>makeqr/ajax_qr",
            {linkto: dataString },  
            function(data){
               var img = data['img'];
               img_rep.attr('src',img);
            },  
            "json"  
        );          
        return false;  //stop the actual form post !important!
 
      });

If you want to see a Demo, I will post a link to it shortly, currently my working copy is under my Auth Controller so you have to login to view it but if enough people ask I’ll post a demo for you, I hope this was a informative article on using jQuery, Bonfire, CodeIgniter and AJAX all in one simple tut.

No tags for this post.

No Comments »

CodeIgniter – Bonfire Series – View Partials from Modules

February 15th, 2012 | by | bonfire, codeigniter, php programming

Feb
15

Series – Using as View Partials

This is one thing that got me a bit confused when I first started using Bonfire, if your gonna use a Module as a View Partial which can be called using the Modules::run method then
you will get a error since the module will be echoed out before the Template is ready. To fix this issue, or a work around for this issue that I use quite a lot is simply to return a view
and remove the Default Template functions from the Module method that I am calling. Since this is a quick tip, I’m not gonna load you down with tons of code just a quick example and a way
to use it.

Now in your Module you should have a method that is called, in this method you instead of using Template::render(); we will simply be returning a view variable, which can be echoed out or
whatever you want to do with it.

Now in your Module Method instead of calling the Template Class we will instead be using CodeIgniter’s default view library, which can be used for returning JavaScript, , whatever, in this
case we will be returning a View Partial to be used in a Theme.

Basiclly at the end of your Module Method, you will replace any Template calls with this

 
  <php>
 
    $data = array (
                   'variables' => $variable,
                   'variable2' => $variable2
                  )
 
    return $this->load->view('modulename/viewfile', $data, true);
  </php>

Now in your Template or Your Block or wherever you want to call this View Partial from you will simply need to add the following code

    <?php echo Modules::run('modulename/method'); ?>

I hope this help’s someone out in the future, in understanding how Bonfire and HMVC work together.

Tags: , , , , , ,

No Comments »

CodeIgniter – Bonfire Series – Introduction

February 15th, 2012 | by | bonfire, codeigniter, php programming

Feb
15

Series – Introduction

I haven’t been blogging lately as much as I used to, this is because I have
been contributing to and learning how to use a new Open Source Project for
CodeIgniter, it’s basically
a prebuilt Admin panel for anything. No this is not another CMS, Blog, etc,
though it can be used for such. Bonfire is a basic starting point for
your web application based on CodeIgniter
and provides you with all the little detail’s that most programmer’s don’t
have time to implement into there software. Such as Secure User Permission’s,
Front End Controller, Auth Controller and a Admin Controller, Database
Migration’s, Log’s, Activities, and even a Module Builder that can even take
your pre-made database table and produce the basic Module code from it, or it
can create the database table based on your needs. Bonfire is already setup
for HMVC CodeIgniter, and has a great community. Currently the latest version
as of this article is .5RC with a very near future Stable Release coming soon.

One Thing I have found that CodeIgniter has been lacking is a Pre-made
Admin Panel and Bonfire fit’s the bill very nicely, I have created 10
different website’s using it and have released
a few for it on Github.

One of the thing’s that really drew me into the Bonfire community was it’s excellent Forums and the fact that it is very well documented, Offer’s a Excellent Template Library, plus Assets
management and many other thing’s that a base project need’s to start with. I personally love Open Source project’s and CodeIgniter has always been my Framework of choice due to the
community and documentation on it, so I naturally I moved to the Bonfire community when I found it. Since Bonfire is a new Project, there are a lack of tutorials out for it, so I’m hoping
to release some of the ones I created and help the community out on understanding how to use Bonfire and how to create excellent website’s with it.

This post is mainly a Introduction to Bonfire itself, I will be explaining How to make Templates, Modules, using Modules as View Partials, Pub/Sub’s, etc, as well as releasing alot of
the module’s I have already created and use everyday. I find the best part of using Bonfire and HMVC in general is that once I build a module, I can copy it from one Website into another
run the database migration’s and change the view if needed and I’m done, no need to re-code things to fit into another web-site, the code is Portable and Re-usable which for Free-lancers
or Business owner’s that means every Module you make is basically a asset that once you create it, you can re-use it over and over again without to much work behind it, which any good
business owner knows once you have your own Asset’s library built up like that you make more money free-lancing or developing.

I hope this article was a good primer on what’s to come, You can find Bonfire or on Github, and of course you can find my module’s
that I have released on Github also.

Tags: , , , , , ,

No Comments »