Archive for the ‘ Code ’ Category

MyGeekScore++

Ah yeah! I have finally done it! I have forked, committed, pushed, sent a pull request and now… I HAVE BEEN MERGED!

12:25 < Fuel-Bot> [oil] philsturgeon pushed 2 new commits to master: https://github.com/fuel/oil/compare/a8e1387…4be84aa                                                   eighty4
12:25 < Fuel-Bot> [oil/master] Making more use of the Form::label() in the scaffold builds – Adam Barrett                                                                    el2ro
12:25 < Fuel-Bot> [oil/master] Merge pull request #18 from utahcon/master – Phil Sturgeon

Today at 12:25MST my pull request for Oil was merged into the master line, which means it is gold!

$geekScore++;

FuelPHP: My new favorite framework

I have posted on FuelPHP once before, and I think it is time I share more about it and why I have chosen it as my PHP Framework of choice.

From FuelPHP.com:

Fuel is a simple, flexible, community driven PHP 5.3 web framework based on the best ideas of other frameworks with a fresh start.

How much clearer can they get?

The Geeks Behind FuelPHP

Dan Horrigan, Phil Sturgeon, Jelmer Schreuder and Harro Verton. If those names mean nothing to you, let me shed some light.

Dan Horrigan

Coding in PHP for 10+ years Dan has contributed to projects like CodeIgniter and PyroCMS, as well as PancakeApp.

Phil Sturgeon

Another great mind behind CodeIgniter. Just look at Phil’s blog, he has done it all!

Jelmer Schreuder

Look through Jelmer’s Github and you can see he is quite experienced as well. He is also super friend in the #fuelphp channel on Freenode.

Harro Verton aka WanWizard

After a long and sordid past as a mainframer he has found roots in programming and contributes a lot of support in #fuelphp as well. He has personally helped me through some of the beginning steps of using FuelPHP.

To all the geeks involved in FuelPHP, a huge thanks!

What Make Fuel Different?

Fuel is young, under a year as of this writing, but already it has seen support and contributions from 30+ developers. The maintainers are really open to anyone committing code cause they believe that since we all use it, we all deserve to support it. Or something like that. Basically if you use it and identify a bug, and you can fix it, then they will let you.

That is probably the best thing about this young framework is the amount of involvement everyone has. Being open source and hosted on GitHub anyone can get the source, and anyone can submit a pull request for changes to the code. I have personally been watching the commits in the IRC channel and I can attest that they are sincere in saying that things are getting done. And fast!

What Make Fuel Awesome?

Gleaming from other great frameworks (and languages) Fuel has been given some great tools. Like Oil.

Oil

Oil is a utility for the CLI that allows you to Generate code, Refine (run tasks, more on this later),  Package (install, update and remove packages) and Console (test code).

Tasks

Tasks are classes that can be run through the command line or set up as a cron job. They are generally used for background processes, timed tasks and maintenance tasks. Tasks can calls models and other classes just like controllers.

Because Tasks actually use the whole framework you can write scripts using the native language of FuelPHP and all things work. All the controllers, all the helpers etc are available to the user.

Lightweight

Autoloading is fun, and useful, but you don’t want to load everything everywhere. Fuel has an extensive (and configurable) configuration to allow you to only load what you want when you want.

Docs

The documentation is a ongoing project, and no where near perfect right now, but it certainly is coming along. Don’t take that to mean it isn’t helpful, cause it absolutely is! Also you can update the docs and commit the changes to the project ;)

ORM and Active Record or just DB

ORM has been done, and done again. FuelPHP has an ORM, or you can opt for ActiveRecord, or if you don’t like either of those you can just use good old SQL. Fuel is flexible and this is a great example of how flexible they really are.

Why Not?!

If you haven’t been sold by my simple blog post on Fuel, then perhaps you need to play with the framework yourself. You can get it from http://fuelphp.com or  from GitHub.

What’s Next?

I am working on a series of blog posts showing how to do things with FuelPHP, so keep tuned for those.

Timezones in FuelPHP

Just thought I would make a note that if you are seeing weird timezones in your FuelPHP programs that you should checkout fuel/app/config/config.php around line 72


/**
 * DateTime settings
 *
 * server_gmt_offset    in seconds the server offset from gmt timestamp when time() is used
 * default_timezone        optional, if you want to change the server's default timezone
 */
'server_gmt_offset'    => 0,
 'default_timezone'    => 'America/Denver'

I have already set these to my local timezone of  ‘America/Denver’ but you can simply comment them out and the default from your php.ini will take effect.

Code Igniter: Hooks

Code Igniter is a great framework, and has some awesome documentation for a lot of what it does, but one place it lacks is in Hooks. What are hooks, how are they used etc, it is explained but not really. So I thought since I just accomplished an awesome example of when to use Hooks in a CI project, I would share it with the world.

What are Hooks?

I’m going to let the folks at Code Igniter field this one:

CodeIgniter’s Hooks feature provides a means to tap into and modify the inner workings of the framework without hacking the core files. When CodeIgniter runs it follows a specific execution process, diagramed in the Application Flow page. There may be instances, however, where you’d like to cause some action to take place at a particular stage in the execution process. For example, you might want to run a script right before your controllers get loaded, or right after, or you might want to trigger one of your own scripts in some other location.

So to clear that up, Hooks let you change the way Code Igniter works, without changing Code Igniter.

10K ft view:

So the problem I had recently was a page that loads a CSS class only when the user selects to change the theme. However it had to be done through a link and had to set the preference in the session to be stored throughout the users session.

To accomplish that I had planned to create a simple controller action called setCssTheme and pass the theme the user had selected. The only problem was I needed to send the user back to the page they had come from, and in some cases the referrer was not being set (different browsers handle things differently).

In order to solve this last problem I had decided to set in the session the last page visited on each page load. This works great in a constructor of a particular class but what if you want to do that site wide, on every single page load like I do?

Force all your site through a single controller? I think not.

Force all your controllers to have this same piece of code? I think not.

Let’s get DRY (Don’t Repeat Yourself).

The solution I decided on was using Hooks in Code Igniter to Hook the system process and set in the session the current page I am on. In order to be able to do this I have to be able to write to the session before the headers are sent to the browser, and so I had to choose the appropriate hook point. CI gives you the follow points to hook in:

  • pre_system
    Called very early during system execution. Only the benchmark and hooks class have been loaded at this point. No routing or other processes have happened.
  • pre_controller
    Called immediately prior to any of your controllers being called. All base classes, routing, and security checks have been done.
  • post_controller_constructor
    Called immediately after your controller is instantiated, but prior to any method calls happening.
  • post_controller
    Called immediately after your controller is fully executed.
  • display_override
    Overrides the _display() function, used to send the finalized page to the web browser at the end of system execution. This permits you to use your own display methodology. Note that you will need to reference the CI superobject with $this->CI =& get_instance() and then the finalized data will be available by calling $this->CI->output->get_output()
  • cache_override
    Enables you to call your own function instead of the _display_cache() function in the output class. This permits you to use your own cache display mechanism.
  • post_system
    Called after the final rendered page is sent to the browser, at the end of system execution after the finalized data is sent to the browser

From those you can see the logic answer is to hook the post_controller so that our controller has a chance to do it’s work, and then to hack in out changes for the session, in this case add data to it.

How To:

Time to put rubber to the road, here is what I had to do to accomplish this task:

  1. Enable Hooks
  2. Configure Hook
  3. Write Hook

Enable Hooks:

To enable the hooks you simply edit

application/config/config.php

and find the line:

$config['enable_hooks'] = false;

and change it to:

$config['enable_hooks'] = TRUE;

Configure Hook:

Now in application/config/hooks.php you need to tell the system what file path, file, controller, method, and parameters you want to run on the hook.

$hook['post_controller'] = array(
  'filepath' => 'hooks',
  'filename' => 'SessionHelper.php',
  'class' => 'SessionHelper',
  'function' => 'setCurrentPage',
  'params' => array(),
);

Here I tell CI that when the controller is done, load hooks/SessionHelper.php and fire off SessionHelper->setCurrentPage() (more or less).

Then I created the file mentioned above as follows:

class SessionHelper extends CI_Hooks {
  public $CI;

  function __construct() {
    parent::__construct();
    $this->CI = get_instance();
  }

  function setCurrentPage(){
    $this->CI->session->set_userdata('current_page', current_url());
  }

This simply loads the current_url() into the session userdata.

Now on every final page load (redirects won’t be caught if they are in the controller) the current_url is stored in the session. So I can check values and redirect back to the current page if needed.

jQuery: Novice to Ninja

I was recently given the opportunity to fly to Florida and hire people to clean up oil from the BP spill. Given that I had some long flights (I live in Salt Lake City, UT) I picked up a Nook from Barnes and Noble and had on my computer a copy of jQuery: Novice to Ninja. What better way to spend my flight time than reading a jQuery book! So I dug in.

I have been using jQuery both professionally and personally for about a year now but this book still brought a lot to the table.

Earle Castedine and Craig Sharkie have a great sense of humor, and obviously know their way around jQuery, CSS, HTML and the likes. The book uses some real world examples of creating image galleries and user interfaces. They break down the jQuery code to it’s basic forms, and then explain why things work the way they do. They don’t get too deep into Javascript except to note that jQuery is nothing more than a fancy framework on top of Javascript and uses Javascript for everything! I thought it particularly neat when they would show the “hard” way to do things, then the better way to do them, and then finally a plugin that made all the work you had just done seem useless, but it isn’t useless because you now understand how the plugin works better than if you had just slapped it in place in the beginning.

The book is quite deep about animations, AJAX actions, DOM manipulation and the sort. Even if you know Javascript and you have been using jQuery there is something in here that will make you go “ah ha!”.

To the folks over at SitePoint (an O’reilly company) good work!

State of Zend Framework 2.0

Matthew Weier O’Phinney has posted about the State of Zend Framework 2.0:

The past few months have kept myself and my team quite busy, as we’ve turned our attentions from maintenance of the Zend Framework 1.X series to Zend Framework 2.0. I’ve been fielding questions regularly about ZF2 lately, and felt it was time to talk about the roadmap for ZF2, what we’ve done so far, and how the community can help.

He goes on to talk about the processes being taken to get Zf2.0 the exemplar of PHP 5.3 and to add namespaces to the project. He talks about his team, the road map and the struggles they have already expereienced:

After completing this process, my entire team — all three of us — started the work of migrating the code to namespaces. Ralph wrote a tool that scanned the library and created a map file of existing classes and suggested namespace/classname combinations. We then used this tool as a launching point for the migration, each of us working on a component at a time. This work was by no means automated — we discovered very quickly that such a tool only took care of the most cursory work. I detailed some of our findings a couple months back; we ran into a number of issues we never anticipated, and the progress has been far from speedy. At this point, however, we have migrated everything but theZend_Service classes, the MVC, and those components that build on top of the MVC (Application, Navigation, Form, etc.).

Finally he shares details about getting ZF2.0 available through Git and Github, and what the community can do to help:

A number of contributors are also starting to discuss rewrites and refactoring of components. Much of this is being done on the zf-contributors mailing list, and some on the #zftalk.dev channel on Freenode. If you are interested in contributing, I highly recommend subscribing to the list and dropping into the channel when you can.

You can read the post in it’s entirety at  http://weierophinney.net

#hackUTOS June 2010

Ceiling Cat

Ceiling Cat

Ceiling Cat announces:

#hackUTOS is is happening tomorrow, Friday June 4th, at CoffeeConnection!

Here’s how it works. #hackUTOS is a gathering of the hacking inclined. There is a main project (ConMan) that is being hacked on for the purpose of volunteering for Utah Open Source Conference 2010. More details on ConMan in a minute.

If you are looking to generally gather with geeks then this is the premier event in June for your geekiness! We will be gathering at CoffeeConnection who has great caffeinated beverages for sale (as well as food) and we will be getting our Geek on.

Want to get your geek on, but can’t make it in person… we are going to be on IRC too! Find us on Freenode at #hackUTOS

If you are not interested in hacking on ConMan, we still encourage you to come on down! We want all geeks to come by and share in the glory of #hackUTOS. That means you can even bring your own project. Think of #hackUTOS as a Jelly or CoWork (for 1 night). Come share your project and your ideas, find people, network, and generally have a good time.

Now some details on ConMan!

ConMan is the Conference Management software used by UTOS for the UTOS Conference. It is written in Python, using the Django framework. It is hosted at GitHub and it is open to the public. If you don’t hack python do not turn and run just yet. We are in need of things besides python coding. We need folks who are willing to conceptualize, we need graphic designers to help make the app look pretty, we need people to help with bug reporting, and more. If you are reading this blog post you are more than qualified to come help us tomorrow (and at any other #hackUTOS event).

Alright… I am tired of typing, and Ceiling cat is starting to freak me out… see you at #hackUTOS

Come Support Open Source!!!

Geek Lunch

Meet at the nearest location to you at 12:30pm this Friday, February 26, 2010.  If you have never been, look for the group with this logo at their table.  Geek Lunch is organized by the Utah Open Source Foundation, but you must pay for your meal.  We look forward to seeing all of you there.

When:

Date: Friday,February 26, 2010
Time: 12:30pm – 2:00pm

Where:

We have geeks all over Utah, and as such we like to spread the love to more than just 1 pub, so we have two (because Utah county is slacking) locations to choose from.

Salt Lake County
The Green Pig
31 East 400 South
Salt Lake City, Utah 84111
Website: http://www.thegreenpigpub.com/
Map: http://snipr.com/uhhox
Phone: (801) 532-7441

Weber / Davis Counties
Roosters
748 Heritage Park Boulevard
Layton, Utah 84041
Website: http://roostersbrewingco.com/
Map: http://snipr.com/uhizp
Phone: (801) 774-9330

Utah County
There is currently no place planned for in Utah county due to low turnout.  If you would like to help organize a Geek Lunch in Utah county, please email clint@utos.org.

ConMan Hack Night

Did you attend UTOSC last year? Are you going to attend this year? Did you like how the process to register and attend was super easy? That is all thanks to ConMan, the Conference Management software that the Utah Open Source Foundation created, and maintains.

If you want to make sure things stay smooth at the conference, and participate in an open source project then you are invited to come down and help us code the project to the next milestone!

Where:

Salt Lake Coffee Connection

1588 South State Street, Salt Lake City UT

Directions

When: 7pm – ??

You see the ?? means you can come and code as late as you want! The coffee house is open really late, and you are welcome to stay and code till they kick you out!

What:

So we get together each week to work on the project, cause we think ConMan can be the best conference management software ever! We simply would love to have some more people who love open source, and know python and django come down and contribute to the code base!

http://saltlakecoffeeconnection.com/map-directions/

PHP, Soap and WSDL Caching

Today I was offered a free lesson in how PHP handles Soap, and more specifically WSDL caching.

When you instantiate a PHP Soap Class you pass it a WSDL (Web Services Description Language) and it looks like this:


$client = new SoapClient('http://example.com/services/thescript.php?wsdl');

Depending on how your caching is setup, this will go out to the WSDL provided, pull in the document and store it in a cache. The default cache for PHP is 86400 seconds. If you are familiar with time in seconds you know that that is 24 hours. So by default you only actually read the WSDL once in a 24 hour period. Normally this is not a problem.

What is a WSDL?

For that answer let’s turn to the W3 site:

WSDL is an XML format for describing network services as a set of endpoints operating on messages containing either document-oriented or procedure-oriented information.

So in English that means it is a map to the services provided by the provider. Basically you get a copy of the map, and follow the endpoints to the answers you need.

One basic function of this is that it tells you want methods (services) are available on your fresh client.

When WSDLs go bad

So today one of my providers, without warning, updated their WSDL. This wreaked havoc on my system because I had cached the WSDL on my side for 24 hours (remember, the PHP default). The change was a super simple change, a change in URL for a service, that’s it!

The problem was that since PHP had already read the file within 24 hours it didn’t care that there was a new file, that the URLs had changed, and so it continued to work as it had before.

The real problem wasn’t that the URLs changed, that would have been fine if the provider hadn’t shut off the previously reported URLs.

Turn off the cache

So you are left with two options when something like this happens. First, you can sit and wait up to 24 hours for the problem to fix itself. This was not an option for us. The second is to clear your cache and try again.

Now PHP (on Linux) stores the cache for the Soap WSDL in /tmp and I wasn’t sure which one of the many files was the actual cache for this particular provider so I decided I would have to tell PHP to not cache the WSDL and try again.

Into php.ini I went, located the soap.wsdl_cache_enabled flag. I changed it from 0 to 1


soap.wsdl_cache_enabled=0

I saved the file and restarted Apache.

The service continued to fail. I was perplexed. I thought maybe I flubbed the save so I opened the php.ini again located my line and it was fine. So I looked around there to see if maybe I missed another important flag. The only thing I could find was soap.wsdl_cache_ttl listed as the “(time to live) Sets the number of second while cached file will be used instead of original one” I promptly changed this to 0 as well


soap.wsdl_cache_ttl=0

Restarted Apache, and finally my script stopped failing.

I have since re-enabled my cache ttl and enabled flags, as reading the WSDL every time is a resource hog that doesn’t need to be in place.

The Lesson Learned

The lesson learned by all today is be aware of your caching, and be aware of the changes you make to your live/production systems.

PHP and Josso – Transparency Rocks!

Bogdan recently asked in my comments:

I can’t seem to find a call like josso_authenticate($name, $pass), returning an array to be appended to user’s SESSION. I was expecting such a method, because SOAP is already used everywhere, so it shouldn’t be too hard implementing this.

Has anyone had success implementing this kind of “transparent” login?

JOSSO simply doesn’t make it easy to log people in with a single call. Instead you need to make an interface to the API to do so. I just so happen to have an example of such a wrapper function.

Read more