Fork me on GitHub

Bgy library by Boris Guéry

Extension of Zend Framework Library

Table of contents

Dependencies

Zend Framework 1.1x

Install

Move Bgy/ into your library/ folder

Register Bgy_ namespace to your autoloader


autoloaderNamespaces[] = "Bgy_"

Components

Bgy_Application_Resource_Doctrine2

Overview

This resource aims to provide a easy way to configure and use Doctrine 2 within a Zend Framework 1.1x project.

It allows you to retrieve a Doctrine\ORM\Configuration object and/or an instance of \Doctrine\ORM\EntityManager.

You can use it to configure your application or the command line tools provided by Doctrine.

Comment

Configuration

Here is a sample application.ini with available options


[production]
pluginpaths.Bgy_Application_Resource = "Bgy/Application/Resource" ; Add custom resource
resources.doctrine2.proxy.dir = APPLICATION_PATH "/proxies"
resources.doctrine2.proxy.autoGenerateClasses = false
resources.doctrine2.proxy.namespace = "\App\Models\Proxies"
resources.doctrine2.metadata.driver = "annotation"
resources.doctrine2.metadata.paths[] = APPLICATION_PATH "/models/Entities/"
resources.doctrine2.cache.result = "\Doctrine\Common\Cache\ArrayCache"
resources.doctrine2.cache.query = "\Doctrine\Common\Cache\ArrayCache"
resources.doctrine2.cache.metadata = "\Doctrine\Common\Cache\ArrayCache"
resources.doctrine2.options.useCExtention = false
resources.doctrine2.options.sqlLogger = "\Doctrine\DBAL\Logging\EchoSQLLogger"
resources.doctrine2.params.driver = "pdo_mysql"
resources.doctrine2.params.dbname = "bgy"
resources.doctrine2.params.host = "127.0.0.1"
resources.doctrine2.params.port = 3306
resources.doctrine2.params.user = "root"
resources.doctrine2.params.password = ""
resources.doctrine2.hydrators.customHydrator = "\Doctrine\ORM\Internal\Hydration\ObjectHydrator"
resources.doctrine2.types.datetime = "Bgy\DBAL\Types\MyDateTimeType"
;resources.doctrine2.events.eventManager = "\Doctrine\Common\EventManager"
;resources.doctrine2.events.subscribers.mysqlSessionInitDefaultParameters = "\Doctrine\DBAL\Event\Listeners\MysqlSessionInit"
resources.doctrine2.events.subscribers.mysqlSessionInit.className = "\Doctrine\DBAL\Event\Listeners\MysqlSessionInit"
resources.doctrine2.events.subscribers.mysqlSessionInit.charset = "UTF8"

[development : production]
resources.doctrine2.proxy.autoGenerateClasses = true

Some options are mandatory while others are optional, please refer to the Doctrine 2 manual.

Setting up autoloader

In order to use the autoloader, you need to register the Doctrine namespace.
In your application.ini:


autoloaderNamespaces[] = "Doctrine"

Note: You don't need to append '_' (underscore) to the pseudo-namespace because Doctrine actually use PHP 5.3 namespace.

Be sure to set up your include path accordingly to your project.
The most convenient way is to place Doctrine/ORM, Doctrine/Common, Doctrine/DBAL and Symfony/* under library/.

Comment

Adding Event Subscribers

Let's say you are using MySQL and you want to init your connection by setting the charset to UTF-8. In plain old (My)SQL you achieve this by querying the following statement: SET NAMES 'UTF8'.
Doctrine 2 already provides such thing within \Doctrine\DBAL\Event\Listeners\MysqlSessionInit.
In order to use it, you need to add it to an EventManager:


use \Doctrine\Common,
    \Doctrine\DBAL\Event\Listeners;
$eventManager = new EventManager();
$eventManager->addEventSubscriber(new MysqlSessionInit('UTF8'));
Using the \Bgy\Application\Resource\Doctrine2, you only need to do this:

;resources.doctrine2.events.eventManager = "\Doctrine\Common\EventManager"
;resources.doctrine2.events.subscribers.mysqlSessionInitDefaultParameters = "\Doctrine\DBAL\Event\Listeners\MysqlSessionInit"
resources.doctrine2.events.subscribers.mysqlSessionInit.className = "\Doctrine\DBAL\Event\Listeners\MysqlSessionInit"
resources.doctrine2.events.subscribers.mysqlSessionInit.charset = "UTF8"

You don't need to specify an EventManager if you want to use the default provided by Doctrine 2.

If you need to provide arguments to the subscriber, you can use the ini array notation as showed in the example above. In this case, you must provide a className option with the actual class name. You can then use either indexed or named keys.

Usage

In your web application

$bootstrap = $this->getInvokeArg('bootstrap');
if ($bootstrap->hasResource('doctrine2')) {
    $doctrine2Resource = $bootstrap->getResource('doctrine2');
    $em = $doctrine2Resource->getEntityManager();
}

You can now store the EntityManager in the Registry, or use it through a Service.

Comment

In doctrine-cli-config.php

// Include paths, require, constants definition, etc.
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);

$application->getBootstrap()
    ->bootstrap(array('doctrine2'));

$em = $application->getBootstrap()
    ->getResource('doctrine2')
    ->getEntityManager();

$GLOBALS['helperSet'] = new \Symfony\Component\Console\Helper\HelperSet(
    array(
        'db' => new \Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()),
        'em' => new \Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em)
    )
);

Change the path of the config file in the doctrine.php cli scripts :


$configFile = getcwd() . DIRECTORY_SEPARATOR . 'configs/doctrine-cli-config.php';

Comment

\Bgy\DBAL\Logging\Firebug

Overview

\Bgy\DBAL\Logging\Firebug is an utility to profile Doctrine 2 SQL queries with Firebug/FirePHP.
It is now really an extension to Zend Framework, as it implements \Doctrine\DBAL\Logging\SQLLogger but makes use of Zend_Wildfire component, and is part of the Zend Framework Doctrine 2 Integration.

Configuration

Using Bgy_Application_Resource_Doctrine2

By default, now logger are used by Doctrine 2, to use this custom logger, specify its classname in your config.ini. Look at the highlighted line :


[production]
pluginpaths.Bgy_Application_Resource = "Bgy/Application/Resource"
resources.doctrine2.proxy.dir = APPLICATION_PATH "/proxies"
resources.doctrine2.proxy.autoGenerateClasses = false
resources.doctrine2.proxy.namespace = "\App\Models\Proxies"
resources.doctrine2.metadata.driver = "annotation"
resources.doctrine2.metadata.paths[] = APPLICATION_PATH "/models/Entities/"
resources.doctrine2.cache.result = "\Doctrine\Common\Cache\ArrayCache"
resources.doctrine2.cache.query = "\Doctrine\Common\Cache\ArrayCache"
resources.doctrine2.cache.metadata = "\Doctrine\Common\Cache\ArrayCache"
resources.doctrine2.options.useCExtention = false
resources.doctrine2.options.sqlLogger = "\Bgy\DBAL\Logging\Firebug"
resources.doctrine2.params.driver = "pdo_mysql"
resources.doctrine2.params.dbname = "bgy"
resources.doctrine2.params.host = "127.0.0.1"
resources.doctrine2.params.port = 3306
resources.doctrine2.params.user = "root"
resources.doctrine2.params.password = ""
Using \Doctrine\DBAL\Configuration

If you don't want to use the custom resource, you can still use this logger by using the Doctrine\Configuration setSQLLogger() setter method.


use \Doctrine\Configuration,
    \Bgy\DBAL\Logging;
    
$config = new Configuration();
$config->setSQLLogger(new Firebug());

Comment

\Bgy\Doctrine\EntitySerializer

Overview

\Bgy\Doctrine\EntitySerializer is an utility inspired by the Doctrine 2 Traits preview from Benjamin Eberlei.

Traits are currently "available" in PHP 5.4 only, I decided to write this component because I was not able to find a clever way to serialize an Entity Object to an Array.
We can use an Array Result as well as writing a custom hydrator, but in some case we just need to cast such object and its relationship to an Array. Most solutions I found until now implemented such serialization in the Entity itself, adding then a dependency to the Entity Manager and therefore the Persistence Layer, which is actually one of the best improvement of Doctrine 2.
The idea behind this component is to be used as a Service which will be used to serialize an Entity.

Configuration

There are no configuration needed except to set up the EntityManager using either the constructor or the setEntityManager() setter method.

Usage

toArray()

Let's say you are using some sort of Dependency Injection and Service Locator, you will have:


public function getEntitySerializerService()
{
    if (!isset(self::$shared['entitySerializer']])) {
        self::$shared['entitySerializer'] = new Bgy\Doctrine\EntitySerializer(
            $this->getEntityManagerService()
        );
    }
    
    return self::$shared['entitySerializer'];
}

Then, for example in your Controller:


public function toArrayAction()
{
    $user = $serviceLocator->getEntityManager()->find('Entity\User', 1);
    $user = $serviceLocator->getEntitySerializer()->toArray($user);
    
    // Do something here
}
toJson()

Serialization to JSON is pretty straightfoward, it is similar to the toArray() method.

Comment

Bgy_Controller_Plugin_AjaxContextDefaultFormat

Overview

This plugin allows you to define a defaut format when using the AjaxContext View Helper.

When using AjaxContext, you need to specify a format to tell the controller which view to return.

For example, in a view script:


$this->url(array(
    'controller' => 'index',
    'action'     => 'delete',
    'id'         => 1,
    'format'     => 'json',    
), null, true);

Zend doesn't check for an Ajax request, instead it uses the format parameter.
Basicly, this plugin check for an XHR request, and set a defaut format (default to 'JSON').
However, you can still override the format parameter when necessary.

Comment

Configuration

In your Bootstrap.php, place the following code:


protected function _initPlugins()
{
    $this->bootstrap('frontController');
    $front = $this->getResource('frontController');
    $front->registerPlugin(new Bgy_Controller_Plugin_AjaxContextDefaultFormat('json'));
}

If you don't provide a default format, JSON is used.

Comment

Usage

None

Bgy_Filter_Scheme_Http

Overview

Bgy_Filter_Scheme_Http prepends the http:// scheme to a given string.
It replaces the current scheme if it is already present and/or malformed before to prepend

Comment

Configuration

There is no configuration for this extension

Usage


$urls = array(
    'borisguery.com',
    'http://borisguery.com',
    'ftp://borisguery.com',
    'htp://borisguery.com',
    'http:/borisguery.com',
    'http:borisguery.com',
);
$filter = new Bgy_Filter_Scheme_Http();
foreach ($urls as $url) {
    var_dump($filter->filter($url));
}

All $url return http://borisguery.com

However, the following example returns 'http://httpborisguery.com' because it has no way to determine if 'http' is part of the domain or not


$filter->filter('httpborisguery.com');

Comment

Bgy_Filter_HotWord

Overview

The main goal of this filter is to wrap a keyword into an html element.

Comment

Configuration


$filter = new Bgy_Filter_HotWord();
$filter->setKeywords(array(
    'consectetur',
    'rhoncus commodo',
    'sollicitudin',
    'dapibus',
    'rhoncus',
));
$filter->setWrapper('%string%');

Comment

Usage

Using the previous configuration, let's say we have the following text:


$text = 'Lorem ipsum dolor sit amet, consectetur rhoncus adipiscing elit. '
 . 'Vestibulum dapibus tortor rhoncus rhoncus commodo fermentum erat gravida '
 . 'sollicitudin. Ut magna diam, tincidunt ac dapibus id, placerat at arcu. '
 . 'Mauris a sapien sit amet risus auctor venenatis et consequat urna. '
 . 'Pellentesque orci erat, gravida vitae rhoncus commodo, laoreet in ipsum. ';

The filtered text will looks like this:


Lorem ipsum dolor sit amet, consectetur rhoncus
 adipiscing elit. Vestibulum dapibus tortor 
 rhoncus rhoncus commodo fermentum erat 
 gravida sollicitudin. Ut magna diam, tincidunt ac 
 dapibus id, placerat at arcu. Mauris a sapien sit amet 
 risus auctor venenatis et consequat urna. Pellentesque orci erat, gravida 
 vitae rhoncus commodo, laoreet in ipsum. 

Note: Keywords can be either a word or a word sequence. The longest word sequence found will be used first, and won't be wrapped twice if it matches a shorter and similar keywords.
Look at the rhoncus and rhoncus commodo keywords for an example.

Comment

Bgy_Filter_Slugify

Overview

Bgy_Filter_Slugify helps you to generate slugs.
Slugs are normalized string free of specials charaters, it is commonly used to generate permalink or product reference.

Comment

Configuration

There are three optional options for this filter:


$options = array(
    'separator' => '~',     // default to '-' (dash)
    'lowercase' => false,   // default to true
    'maxlength' => 35,     // default to null (no maxlength)
);

You can either provide, an array, a Zend_Config object or function arguments in the same given order.
Example:


$filter = new Bgy_Filter_Slugify('~', false, 35);

Comment

Usage

Using the previous configuration, the filtered value returns:


$value = 'http://ßorisGuéry.GithüB.com/BgyLibräry/';
echo $filter->filter($value);

// returns (note the (ß) Eszett and others accented charaters)

'http~ssorisGuery~GithuB~com~BgyLibr'

Note: The length is computed after the string being slugified, and if a separator is present at the end of the string, it is trimed. Therefore, the resulting length may be different.

Comment

Bgy_Service_Geonames

Overview

Geonames is a geographical database and webservice free of charge under a creative commons attribution license. To know more about Geonames, visit their website.

Bgy_Service_Geonames is a webservice wrapper which respects the Zend Framework

Comment

Configuration

Note: According to this announcement the username is now mandatory (if you use the new URI: api.geonames.org)

To configure your username and token, you can pass an array, or an instance of Zend_Config to the constructor:


$options = array(
    'username' => 'borisguery',
    'token'    => 'abcdef0123456789'
);
$g = new Bgy_Service_Geonames($options);
Alternatively you can set both with their respective setters:

$g = new Bgy_Service_Geonames();
$g->setUsername('borisguery')
    ->setToken('abcdef0123456789');

Comment

Usage

Most of the methods provided by the Geonames webservices are available.

The following static method returns a complete list of the supported methods:


Bgy_Service_Geonames::getAvailableMethods();

Bgy_Service_Geonames uses the magic method __call() therefore all methods have the same signature.


/**
 * @method array postalCodeCountryInfo()      postalCodeCountryInfo(array $params)
 * @method array postalCodeLookup()           postalCodeLookup(array $params)
 */

For a complete list of the available and mandatory parameters, see the Geonames webservice manual.

Errors are also handled by the wrapper, and throw a Bgy_Service_Geonames_Exception with the message returned by the webservice.
See the manual for a description of the errors.

Comment

Examples

Retrieve informations for a given postal code


$result = $g->postalCodeLookup(
    array(
      'postalcode' => '13100',
      'country'    => 'FR',
      'maxRows'    => 1,
    )
);

// returns

array
  0 => 
    array
      'adminCode3' => string '131' (length=3)
      'adminName2' => string 'Bouches-du-Rhône' (length=17)
      'adminName3' => string 'Arrondissement d'Aix-en-Provence' (length=32)
      'adminCode2' => string '13' (length=2)
      'postalcode' => string '13100' (length=5)
      'adminCode1' => string 'B8' (length=2)
      'countryCode' => string 'FR' (length=2)
      'lng' => float 5.55
      'placeName' => string 'Beaurecueil' (length=11)
      'lat' => float 43.5
      'adminName1' => string 'Provence-Alpes-Côte d'Azur' (length=27)

Retrieve informations for a given postal code


$result  = $g->findNearbyPlaceName(
    array(
      'lng'     => 5.55,
      'lat'     => 43.5,
      'lang'    => 'FR',
      'style'   => 'short',
      'maxRows' => 2,
      'radius'  => 10,
    )
);

// returns

array
  0 => 
    array
      'distance' => string '1.36754' (length=7)
      'toponymName' => string 'Beaurecueil' (length=11)
      'fcl' => string 'P' (length=1)
      'name' => string 'Beaurecueil' (length=11)
      'countryCode' => string 'FR' (length=2)
      'lng' => float 5.5456924438477
      'fcode' => string 'PPL' (length=3)
      'geonameId' => int 3034099
      'lat' => float 43.511895697594
  1 => 
    array
      'distance' => string '1.94964' (length=7)
      'toponymName' => string 'Châteauneuf-le-Rouge' (length=21)
      'fcl' => string 'P' (length=1)
      'name' => string 'Châteauneuf-le-Rouge' (length=21)
      'countryCode' => string 'FR' (length=2)
      'lng' => float 5.5692100524902
      'fcode' => string 'PPL' (length=3)
      'geonameId' => int 3026229
      'lat' => float 43.489358035839

Comment

Bgy_View_Helper_RelativeDateTime

Overview

Bgy_View_Helper provides a efficient and configurable way to generate a relative date/time string from a given Zend_Date object.

Comment

Configuration

First you need to set up your View object to use your custom View Helper.
Somewhere in your Bootstrap.php:


$this->bootstrap('view');
$view = $this->getResource('view');
$view->addHelperPath(
    APPLICATION_PATH . '/../library/Bgy/View/Helper',
    'Bgy_View_Helper_'
);

Comment

Usage

Let's say we have the following dates string, and current date is 2011-02-22T:20:59:15.
In your view scripts:


$relativeDateTime = new Bgy_View_Helper_RelativeDateTime();
$dates = array(
    '2010-01-01',
    '2010-06-01',
    '2010-12-01',
    '2011-02-01',
    '2011-02-20',
    '2011-02-22T19:50',
    '2011-02-22T20:58',
    '2011-02-22T20:59:12',
);
$dates = array_map(function($a){return new Zend_Date($a);}, $dates);
        
foreach ($dates as $date) {
    echo $relativeDateTime->relativeDateTime($date) . '
'; }

The following code returns:


1 year
8 months
2 months
3 weeks
2 days
1 hour
19 minutes
1 minute
3 seconds

Now if we want to change the way the result will be formated, we can use the following method setUnitTemplate($unitKey, $template) and setUnitTemplates(array $templates)

Here is an example using the previous code:


$relativeDateTime = new Bgy_View_Helper_RelativeDateTime();
$relativeDateTime->setUnitTemplate(Bgy_View_Helper_RelativeDateTime::DAYS, 'there are %value% days ago');

Alternatively you can do:


$relativeDateTime = new Bgy_View_Helper_RelativeDateTime();
$templates = array(
    Bgy_View_Helper_RelativeDateTime::DAYS => 'there are %value% days ago',
);
$relativeDateTime->setUnitTemplates($templates);

returns:


there are 2 days

The helper use Zend_View_Helper_Translate which means you can translate your template in your prefered translate format (either CSV, gettext, XML, etc.) and they'll be translated automatically.

Comment

License

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
                    Version 2, December 2004

 Copyright (C) 2004 Sam Hocevar «sam@hocevar.net»

 Everyone is permitted to copy and distribute verbatim or modified
 copies of this license document, and changing it is allowed as long
 as the name is changed.

            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. You just DO WHAT THE FUCK YOU WANT TO. 

Author

Boris Guéry (guery.b@gmail.com)

Download

You can download this project in either zip or tar formats.

You can also clone the project with Git by running:

$ git clone git://github.com/borisguery/bgylibrary

Comments