Posts Tagged ‘Server Side’

7Oct

Lately I’ve been working on a client/server side validation library. I had a need to chain a bunch of methods together, and what that meant was a need to modify how the original functions were called without changing them. This lead to a need to pass some variables into a function and still wait to accept more parameters later. I already knew about currying, which I will summarize as being able to pass as many variables as you feel into a function. A couple other techniques were needed to solve this.

First I learned about the apply and call functions (I know I am late to the party…). In this case apply was extremely helpful, it let me set a context (change the value of this) and collect some parameters together and pass them into a function.

Next I discovered partial applications. This is more of a technique than anything else. In iz we have the following source code:

function validator_partial(fn) {
    //get all arguments except the first, which is the function name
    var args = Array.prototype.slice.call(arguments, 1);
    //pass the "value" in as the first parameter so that the user of this library doesn't need to
    args.unshift(value);
    //return a new function
    return function() {
        //combine all arguments made to this function with the ones above
        var allArguments = args.concat(Array.prototype.slice.call(arguments)),
        //get the result
        result = validators[fn].apply(null, allArguments);
        //update this object
        if (!result) {
            if (typeof this.error_messages[fn] !== "undefined") {
                this.errors.push(this.error_messages[fn]);
            } else {
                this.errors.push(fn);
            }
            this.errors.push(fn);
            this.valid = false;
        }
        //return "this" to allow for chaining of methods
        return this;
   };
}

for (var fn in validators) {
    //for each function, call the partial and pass in the function
    if (validators.hasOwnProperty(fn)) {
        Iz.prototype[fn] = validator_partial(fn);
    }
}

At the bottom I am grabbing the validators, and assigning them to the prototype of the Iz object. Before the validators get called though they go through a partial. This partial is a function that returns a function. The closure allows you to house some variables within it. When the returned function gets called it has access to the outer one’s scope, which is how you are able to pass in parameters before and after the function is called. On top of that this system lets you pass in as many params as you need and it simply forwards everything on.

With this method I was able to replace all of the first parameters (the ‘values’ with the value from the Iz object. This means less typing, which is always nice!

Share
27Mar

This is somewhat based off of the articles found in the bakery at cakephp.org; however, I will be expanding on those tutorials a bit. First of all, everyone likes fancy loading bars or spinners so here is a good site that will handle creating that for you: http://www.ajaxload.info/

One of my main challenges today was trying to properly narrow the results in each page depending on the category within the site I am located. This was not quite obvious. Another problem I had was trying to get data from other models. The first was more easily solvable. The second required me to use a request action. I am looking for a more elegant solution, but until then this gets the job done.

My controller is simple:


function cat($catId){
//Configure::write('debug', '2');
if(!$this->RequestHandler->isAjax()) {

}

$this->set('cat',$this->Event->EventCategory->find('first',array('conditions'=>array('EventCategory.id'=>$catId),'fields'=>array('EventCategory.id','EventCategory.cat_name'))));
$this->set('catId',$catId);
$this->set('events', $this->paginate(null, array('Event.event_category_id' => $catId,'Event.event_date>=curdate()')));

if($this->RequestHandler->isAjax()) {
$this->viewPath = 'elements'.DS.'events';
$this->render('paging');
}
}

The important line is where I set events with the call to paginate. This allows me to limit the results in the same why I would use find. Unfortunatly, unlike find it will not retrieve associated results.

View for cat


echo $javascript->link("prototype",false);
echo $javascript->link("scriptaculous/scriptaculous.js",false);
echo $javascript->link("columns/matching_columns",false);
//$paginator->options(array('update' => 'CatPaging', 'indicator' => 'LoadingDiv'));
?>
<div id="LoadingDiv" style="display: none;">
image('ajax-loader.gif'); ?></div>
<div id="CatPaging">
renderElement('events/paging'); ?></div>

elements/events/paging.ctp


$paginator->options(
array('update'=>'CatPaging',
'url'=>array('controller'=>'Events', 'action'=>'cat'),
'indicator' => 'LoadingDiv'));
?>
<div style="width: 100%; position: relative; float: left;">

// stuff here

</div>
<div style="margin: 15px 0pt; width: 100%; position: relative; text-align: center; float: left;">
prev('<<',array('url'=>$this->params['pass'])); ?> .
numbers(array('separator'=>' . ','url'=>$this->params['pass'])); ?> .
next('>>',array('url'=>$this->params['pass'])); ?></div>

I had to use the ‘url’ option and use $this->params[‘pass’] so that my url including the parameter transfered over to the pagination. Now I can use pagination within the categories of my events model! Not too bad.

I hope this helps someone! I was tweaking it for a few hours today. I hope it saves someone a little time.

Here it is in action: http://www.letswoosh.com/events/cat/1 (of course this is assuming I have at least 7events posted, right now there are 7. So tomorrow it may look like nothing is happening 🙁 )

Enjoy!

Share
19Aug

I decided I would give you guys a mini update on work and such. So a few weeks ago I wrapped up my cable customizer 3000 project for spectraflex.com. The idea was to make a way to “create your own customized cable online and see a preview.” That is quite a task. There are over 140 possible combinations between colors and patterns. So we did it the good old fashioned way and took pictures of every single cable the exact same way. Then we created some javascript to update a picture on change and used some cool javascript effects to make it appear in an intruging way. Bottom line, it took way longer than we anticipated! Try it out for yourself though :)!!! Here is the link to one of the products: http://www.spectraflex.com/products.php?req=read&product_id=11
By the way, it is on every page that has color and pattern options!

Share
19Jul

When I first started using CakePHP I was stuck for about 3 to 4 days with associations. After scouring the web, reading probably about 100 articles I have realized they are quite confusing when you first start with out using cake. I am hoping this post assists other people who were in my position for the past 3 days.

Associations are used for those tasks where you need to look up a row or multiple rows in another table based on an id number of sorts. The first thing to do in CakePHP is to make sure you have all the conventions correct to the very last point. If you want to make it really easy on yourself also I would recommend following their database naming conventions also. Here is a mini checklist:

  • Model file names, var $name, and class names are singular
  • Controller class names and var $name are plural also the file name is the plural version of model name followed by _controller.php
  • The folder name for a view is plural and the file name should match the “action” name or function name in the controller followed with the extension .thtml
  • Every table in your database should be the plural form of the model name.
  • The primary key of each table should be id
  • The associated key should be the name of another table singularly followed by _id (eg. I have a table named event_catogires, then in events my associated column name should be called event_category_id)

As far I can think right now. I think that may be all the key ones. If you have all the above correct the rest should be a breeze. I will now show you how I got something like a category name to appear next to a title of an article. This example isn’t meant to be copied. I don’t give enough information for that, but I hope this leads you guys in the right direction.

The Model:

class Event extends AppModel
{
var $name = 'Event';
var $useTable = 'events';
var $belongsTo = array('GalleryCategory' , 'EventCategory');

}

We are saying Event $belongsTo or $hasOne of each of these models (‘GalleryCategory’ , ‘EventCategory’). When find is called in the controller it will look up the following models and bring up that single row we are looking for in each of these.

The Controller:

class EventsController extends AppController
{
var $name = 'Events';

function index()
{
$this->set('events', $this->Event->findAll());
$this->set('title', 'All Events');
}
}

Now I won’t show the view because it doesn’t really matter. You could just enable scaffolding if you had wished. $this->set(‘events’, $this->Event->findAll()); set up a variable named events so that in the view we can retrieve an array with all database fields. This includes the rows that were found set up in the belongs to of the events model. You will need to make a model and controller for every related table.

On the reverse side. Let us say you wanted to show all events with a event_category. Then all you need to do is simply use the following line rather than belongsTo:

var $hasMany = 'Events';

There are other associations, but I feel that these 2 would be the most used. For example if you had something like tags which unlike categories have and belong to many pages you would use: var $hasAndBelongsToMany = ‘Events’;.

The most import thing to get this stuff to work is following the conventions. If you don’t everything falls to pieces somethings work, somethings don’t and you will have holes in your system.

If you have any questions feel free to post a comment. I am a beginner with cake myself, but I am hoping by the end of august I will be a pro haha.

Share