RSS
 

Posts Tagged ‘Helper’

Gravatar CakePHP Helper

23 Aug

An independent Avatar-Generator

90% of all blogs out there use gravatar. Therefore you can easily use it with most of your users’ email addresses.
But even if you don’t want your users to use their gravatar image you can still use the funny images this service provides. Instead of an email address you could hash the user_id of the member and get a unique image to display as avatar in the profiles or even throughout the website.

Resources:
Gravatar Helper and its Test Case.

Example usage

# using the email of the user
echo $this->Gravatar->image($email, array('default'=>'retro', 'title'=>__('Avatar', true)));
 
# using an unique identifier - in this case the user_id
echo $this->Gravatar->image($uid, array('size'=>'20', 'default'=>'monsterid', 'title'=>__('Avatar', true)));

The first example will try to find the real image the user has submitted to gravatar and will fallback to some colorful and unique retro image.
The second example uses little monster figures for all users (since the user_id cannot be an email and therefore there cannot be any custom user image – except for collisions with the md5 hash maybe).

Tip: check out the test case for all possible image types, options and scenarios.
If you open my test case with the browser (…/test.php?case=helpers%5Cgravatar.test.php&plugin=tools) you will see the images as I echoed them out for testing purposes.

The main part of this helper is the work of Graham Weldon. I simply added some enhancements.
Hava fun.

 
No Comments

Posted in CakePHP

 

GoogleMapsV3 CakePHP Helper

21 Dec

Google Maps V2 is marked “deprecated”. V3 is supposed to be faster and more compatible to mobile browsers. Details
Also new: A googlemaps key is not necessary anymore.

UPDATE: v1.1 (March 2011) – not backwards-compatible

Usage

I wanted to keep it as simple as possible (otherwise you could use the maps with plain js right away).

You may set up configs/defaults in your config file:

$config['Google'] = array(
	'zoom' => 6,
	'lat' => 51.1,
	'lng' => 11.2,
	'type' => 'H', # Roadmap, Satellite, Hybrid, Terrain
	'size' => array('width'=>'100%', 'height'=>400),
	'staticSize' => '500x450',
);

Now you need to add the helper to the controller (or the action):

# globally
public $helpers = array(..., 'GoogleMapV3');
# OR in the action:
public function map() {
	$this->helpers[] = 'GoogleMapV3';
	# rest of your code
}

Since there are many possible ways to include the required javascript file I formed an own method for it:

<?php
# include Jquery 1.4
$this->Html->script('jquery'); # or wherever it is in your js folder

# include the map js code
$this->Html->script($this->GoogleMapV3->apiUrl());
 
# OR include it manually without cake (or use your own asset stuff)
echo '<script type="text/javascript" src="'.$this->GoogleMapV3->apiUrl().'"></script>';

You may also let the helper include it automatically – just pass the option “autoScript” => true to the map() method in the next step.

Now we can use it.

Interactive Maps

# init map (prints container)
echo $this->GoogleMapV3->map(array('div'=>array('height'=>'400', 'width'=>'100%')));
 
# add markers
$options = array(
	'lat' => 48.95145,
	'lng' => 11.6981,
	'icon'=> 'url_to_icon', # optional
	'title' => 'Some title', # optional
	'content' => '<b>HTML</b> Content for the Bubble/InfoWindow' # optional
);
# tip: use it inside a for loop for multiple markers
$this->GoogleMapV3->addMarker($options);
 
# print js
echo $this->GoogleMapV3->script();

You can also add windows and (custom) events. See the code for details on that.

Static Maps

These are just images. Very handy if you don’t need the js overhead.

# markers
$markers = array(
	array('lat'=>48.2, 'lng'=>11.1),
	array('lat'=>48.1, 'lng'=>11.2, 'color' => 'green', ...)
);
# paths
$paths = array(
	array(
		'path' => array('Berlin', 'Stuttgart'),
		'color' => 'green',
	),
	array(
		'path' => array('44.2,11.1', '43.1,12.2', '44.3,11.3', '43.3,12.3'),
	),
	array(
		'path' => array(array('lat'=>'48.1','lng'=>'11.1'), array('lat'=>'48.4','lng'=>'11.2')), //'Frankfurt'
		'color' => 'red',
		'weight' => 10
	)
);
 
# some options and image attributes
$options = array(
	'size' => '500x400',
	'center' => true,
	'markers' => $this->GoogleMapV3->staticMarkers($markers),
	'paths' => $this->GoogleMapV3->staticPaths($paths),
);
$attr = array(
	'title'=>'Yeah'
);
 
# now display the map image
echo $this->GoogleMapV3->staticMap($options, $attr);
 
# you can even add an url to click on
$attr['url'] = $this->GoogleMapV3->url(array('to'=>'Munich, Germany'));
echo $this->GoogleMapV3->staticMap($options, $attr);

As you can see, we can now mix lat/lng and normal addresses (which get automatically geocoded in the background).

Map Links

If you want to redirect to maps.google.com (for directions etc) you can use this method.

# leave "from" empty for the user
$url = $this->GoogleMapV3->url(array('to'=>'Munich, Germany'));
echo $this->Html->link('Visit Me', $url, array('target'=>'_blank')
 
# coming from a posted form or whatever
$url = $this->GoogleMapV3->url(array('to'=>'Munich, Germany', 'from'=>$from));
echo $this->Html->link('Directions to me', $url, array('target'=>'_blank')

Last but not least

Other updates:
- multiple paths and markers
- visible scope
- custom icons possible

For more examples check out the test case. It contains several more sophisticated examples.

Helper Code

While it is still under development (pending improvements), the code can be found in my github rep:
github.com/dereuromark/cakephp-google-map-v3-helper

 
41 Comments

Posted in CakePHP

 

Helper? Component? Lib?

26 Jun

Some ideas what to use if you want to add some additional feature.
Feel free to comment on this below.

Level of Independence

We need to ask ourselves if this feature needs to interact with other cake elements, like controller, some components, models, …

If it needs to save to the session, or if it needs some controller functionality, it will have to be a component.
With initialize(&$controllerReference) and startup(&$controllerReference) this is very easy to accomplish.

But with Cake13 libs have been introduced. Not every piece of “controller” code necessarily needs to be component anymore.
So if you retrieve an RSS feed or get the weather from a weather channel web service you could just make a clean and independent lib class. No need to extend the cake object or even pass the controller reference. Less memory and dependency is a good thing. And its easier to test, anyway.

Helpers are used if the result is in relation to the view – in other words if it gets printed/echoed right away. If you want to retrieve some web service information and save it to the database use a component instead.

Database related?

Often times we need to adjust some model data, we either use a component first and then pass it to the model or we use beforeValidate() and beforeSave() in the model. Same goes for the other direction (from model to controller): afterFind() or a component call afterwards.
This is fine for custom changes. As soon as it could be something useful for several models, it might make sense to build a behavior. The code gets cleaner and your models more powerful.

Examples would be:
“Last Editor/Last Change”, “Geocoding”, “Auto-Capitalize first letter of name/title”, “Format/Localize Date/Time”, …

Reducing code redundancy

Now that we have a vague understanding where to use what type of tool, we should think about cutting down the redundancy.
Lets say we use the vendor class “phpThump”. We would have to write two wrappers. one for the helper (display images in the view) and one for the component (uploading images and resizing), maybe even for some behavior (validating + uploading + resizing). This wrapper handles default values from Configure::read() and other cake related settings.
In this scenario we should build one single library in /libs, maybe called “phpthumb_lib.php”.
Here we put our wrapper with our custom functions.
Then we build a helper (view side) as well as a component or a behavior (controller side). They will import and use the library file. This is a cleaner approach because changes in the library class will be available in all files it is used in.
Bonus: The main library file is easier to test. And therefore testing the other classes afterwards is easier, too.

Generally speaking, all web services should be some kind of library file (some would make a data source out of it). It doesn’t matter then if we use it in components or helpers, because it will fit either way.
A helper in a controller, though, is not really a nice thing.

Thats – by the way – something i don’t like about the core helpers. They have functionality which is often useful in the controller (replacing a timestamp with localized date in session flash messages).
So there should be a library called “Time” or whatever which is then extended or used in the helper.
But, if needed, it can be used in the controller, as well. Same goes for “Text” and “Number”.

Plugin or not?

If your feature is not site-specific but very generic it probably makes sense to build a plugin.
This way all other apps can easily use the same plugin. Additionally, test cases, assets etc are all combined in one folder – clean and extendable.

Examples:
A bookmark helper usually can be used in several apps, whereas a custom helper with two functions for this one app will not be very useful anywhere else.

Usage of those resources

For components, add it to the controller in order to use it in the corresponding actions:

var $components = array('MyC'); # file is in /app/controllers/components named my_c.php

And in one of the controller’s actions:

$this->MyC->foo();

For helpers, add it to the controller in order to use it in the corresponding views:

var $helpers = array('MyH'); # file is in /app/views/helpers named my_h.php

And in one of the controller’s views:

$this->MyH->foo();

Libs can be used everywhere – include them at runtime:

App::import('Lib', 'MyL'); # file is in /app/libs named my_l.php
$myL = new MyL();
$myL->foo();

Possible in controllers, components, behaviors, view, helpers, elements and everything else.

Behaviors and other elements are used similar to the above.

For Plugins simply add the plugin name: “Text” becomes “Plugin.Text” etc

Hacks for special use cases

Sometimes we need to break MVC in order to avoid redundance (and stay DRY).
A typical szenario is when we need a core helper in the controller (e.g. TextHelper).
We need to manually include it then at runtime:

App::import('Helper', 'Text');
$text = new TextHelper();
$myText = $text->truncate($myText);

I want to emphasize that this should only be done if not possible any other way.
You would also have to manually start and attach all helpers which are used inside the helper. Pretty annoying :)

I proposed a while ago that most of the core helpers should actually extend or at least use libs which contain the relevant functionality.
This way we can use the libs in the controller and we can use their methods in the view via helper wrappers.
But as of right now this is not yet planned for Cake2.0 or higher.

 
No Comments

Posted in CakePHP