Skip to content

Zend Framework 2 - Lazy Factory - Kickstarter (for ZF 2.4)

No blabla, just how you do it with zend framework 2.4.

#add following line to your composer.json
"ocramius/proxy-manager": "1.0.*",

composer update

#add following lines to your module.config.php
'lazy_services' => [
    'class_map' => [
        \My\Class::class => \My\Class::class
    ]
],
'service_manager' => [
    'delegators' => [
        \My\Class::class => [
            \Zend\ServiceManager\Proxy\LazyServiceFactory::class
        ]
    ],
    'factories' => [
        \My\Class::class => \My\ClassFactory::class,
        \Zend\ServiceManager\Proxy\LazyServiceFactory::class => \Zend\ServiceManager\Proxy\LazyServiceFactoryFactory::class
    ]
]

Thats it.

Useful links are a gist from a closed issue and somehow an official howto (maybe working with zend framework greater 2.4).

Translate to de es fr it pt ja

zf-rest - error "title":"Not Found","status":404,"detail":"Entity not found."

I configured the routes as well as the other parts pretty well.
An important step to solving the issue was adding the following configuration section into my project "local.php".


    //this is possible overwritten by the zf-rest module
    'view-manager' => array(
        'displayexceptions' => true,
        'displaynotfoundreason' => true
    )

After that, I got back an response with the following content:
{"type":"http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html","title":"Not Found","status":404,"detail":"Entity not found."

After adding a lot of debugging statements in the "ZF\Rest\RestController" (search for "Entity not found." ;-)), started understanding the issue.
The answer is pretty clear after all. Whenever you listen on a GET HTTP Method with your listener, you have to return an array with the configured "routeidentifiername" (the entity identifier), otherwise the controller as well as the HAL post processor is not able to successful build the response.

Translate to de es fr it pt ja

zend framework 2.4 "Zend\ServiceManager\Exception\ServiceNotFoundException: Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for ApplicationConfig"

We had some controller tests in our test cases and the following error was thrown, after we updated to zend framework 2.4.


Zend\ServiceManager\Exception\ServiceNotFoundException: Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for ApplicationConfig

/vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:555 /vendor/zendframework/zendframework/library/Zend/Mvc/Service/ModuleManagerFactory.php:41 /vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:939 /vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:1097 /vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:638 /vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:598 /vendor/zendframework/zendframework/library/Zend/ServiceManager/ServiceManager.php:530 /vendor/zendframework/zendframework/library/Zend/Mvc/Application.php:253 /vendor/zendframework/zendframework/library/Zend/Test/PHPUnit/Controller/AbstractControllerTestCase.php:164 /vendor/zendframework/zendframework/library/Zend/Test/PHPUnit/Controller/AbstractControllerTestCase.php:73 //MyControllerTest.php:124

"MyControllerTest" extends "Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase". What we did to solve the problem was adding the following lines of code in our "setUp" method.

$applicationConfigurationPath = DIR . strrepeat('/..', ) . '/config/application.config.php';
if (!isfile($applicationConfigurationPath)) {
    $message = 'application configuration needed and not found in path "' . $applicationConfigurationPath . '"';

$this->fail($message);

} $applicationConfiguration = require $applicationConfigurationPath; unset($applicationConfiguration['modulelisteneroptions']['configglobpaths']); $applicationConfiguration['modules'] = array();

$this->setApplicationConfig($applicationConfiguration);


Thats it, hope it helps.

Translate to de es fr it pt ja

New versions of the zend framework 2 console helper family available now

I happy to announce the release of 1.1.0 of bazzlines zend framework 2 console helper (debian backport) module for php as well as the release of 1.1.0 of bazzlines zend framework 2 console helpermodule for php.
Important changes are:

  • added AbstractConsoleControllerFactory
Translate to de es fr it pt ja

Updated Zend Framework 2 Modules because of the locator generator version 2.0.0 release

I announced already, version 2.0.0 of the "locator generator" is out.
Because of that, I am also happy to announce the release of 1.4.1 from the zend framework 2 "locator generator" module.
Furthermore, the debian 6/PHP 5.3 backport got the release of version 1.3.0.
And finally, and because of the fact that zend framework 2.5.* is dropping support for PHP 5.4, the new debian 7/PHP 5.4 got the release of version 1.7.0.
Major changes in all releases is the dependency update to the new locator generator version.

You want to have a quick look and tryout without any hassle? Try the zf demo environment available in three flavors, cutting edge, debian 7/PHP 5.4 backport and debian 6/PHP 5.3 backport.

Translate to de es fr it pt ja

php - zfcampus/zf-rest how to | tutorial

Assuming you are using the Zend Framework 2 and want to implement a REST endpoint in a quick and fully functional way.
ZF-Rest is, more or less, the official rest module for zf2. But, the documentation is not available - nor planned right now. Thats why I this blog entry will boost your knowledge and speed up the time until you have finished your first zf2 rest endpoint.

Installation and Setup

add the following line to you composer.json

"zfcampus/zf-rest": "1.0.3"

You need to add the following entries in your to "config/autload/application.config".


<?php

return array( 'modules' => array( //your modules 'ZF\ApiProblem', 'ZF\ContentNegotiation', 'ZF\Hal', 'ZF\MvcAuth', 'ZF\OAuth2', 'ZF\Rest' );

Minimal Configuration (module.config.php)

array key "zf-rest"


//MyRestController is a virtual Controller 
'My\Module\Namespace\MyRestController' => array(
    //mandatory - available are GET, POST, PUT, PATCH, DELETE
    'collectionhttpmethods'       => array(
        'GET'
    ),
    //mandatory - available are GET, POST, PUT, PATCH, DELETE
    'entityhttpmethods'           => array(
        'GET'
    ),
    //virtual name - its the name the collection entries are getting in the HAL-repesentation
    'collectionname'               => 'items',
    'routename'                    => 'myrestroutename',
    'routeidentifiername'         => 'id',
    //this is the only file you really need to code/implement
    'listener'                      => 'My\Module\Namespace\MyListener'
),

array key "router/routes"


'myrestroutename' => array(
    'type' => 'Zend\Mvc\Router\Http\Segment',
    'options' => array(
        'route' => '/my/rest/endpoint/[/:id]',
        'defaults' => array(
            //MyRestController is a virtual Controller
            //The name is needed to map the module configuration to the endpoint
            'controller' => 'My\Module\Namespace\MyRestController'
        )
    ),

Optional Configuration Values

Based on the source code from RestControllerFactory.php, following configuration keys are optional (mention as mandatory in the current README.md).

  • resourceidentifiers
  • identifier
  • controllerclass
  • entityclass
  • collectionclass
Translate to de es fr it pt ja

version 1.0.2 of zend framework 2 console helper (debian 6 backport) released

I happy to announce the release of 1.0.2 of bazzlines zend framework 2 console helper (debian backport) module for php. Important changes are:

  • removed dependency to apigen
  • updated dependencies
Translate to de es fr it pt ja

version 1.3.3 of zend framework 2 locator generator released

I happy to announce the release of 1.3.3 of bazzlines zend framework 2 locator generator module for php. Important changes are:

  • updated dependencies
  • removed apigen dependency
  • fixed dependency issue
  • added factory for controller creation
  • updated to locator generator 1.4.0
  • added documentation @todo - add link
  • added migration
  • added link to debian 6 / zend framework 2.2 backport
  • prefixed console commands with "net_bazzline" to not pollute the available command environment
Translate to de es fr it pt ja

version 1.0.3 of zend framework 2 console helper released

I happy to announce the release of 1.0.3 of bazzlines zend framework 2 console helper module for php. Important changes are:

  • removed apigen dependency
  • added use statement into example
  • added link to demo environment
  • added link to debian 6 / zend framework 2.2 backport
  • added minimum version of zend framework 2 to 2.3.* since AbstractConsoleController is mandatory
  • updated dependencies
Translate to de es fr it pt ja

version 1.2.2 of zend framework 2 locator generator (debian 6 backport) released

I happy to announce the release of 1.2.2 of bazzlines zend framework 2 locator generator module for php. Important changes are:

  • added factory for controller creation
  • added migration
  • update dependencies
  • removed dependency from apigen
Translate to de es fr it pt ja

version 1.0.0 of zend framework 2 console helper (debian 6 backport) released

I am happy to announce the release of 1.0.0 of bazzlines zend framework 2 console helper module for php.
It is a backport of the existing locator generator module.

Translate to de es fr it pt ja

version 1.0.0 of zend framework 2 locator generator (debian 6 backport) released

I am happy to announce the release of 1.0.0 of bazzlines zend framework 2 locator generator module for php.
It is a backport of the existing locator generator module.

Translate to de es fr it pt ja

Apigility and Pair Programming - PHPUGHH

PHPUGHH

Apigility by Ralf Eggert

Whats the problem?

  • new api in two hours
  • do rapid prototyping

In a nutshell

  • create a RESTful web services quick
  • create a rpc web service
  • supports versioning per url or negotiation (content type)
  • returns JSON and HAL JSON out of the box
  • authentication (database, code based, other)
  • api documentation
  • data validation (zend filtering)
  • supports deployment
  • modular based

Example

  • databased rest service
  • see slides for steps
  • good for easy stuff or complex stuff
  • good for rapid prototyping of see how the modules are working

To pair or not to pair by Sebastian Schürmann

About Sebastian

  • freelancer developer, coach, trainer
  • first contact to xp in 2005
  • scrum since 2008
  • loves open source
  • blog
  • mail

@s0enke

  • reduce bus factor
  • improve teamwork
  • improve learning

Pair Programming

Prefrace

  • pair programming illuminated (book)
  • specification by examples (book)
  • workshop

Critics

  • two programmers doing the work of one

Thesis

  • working alone, undistrubed is good
  • talking is disturbance which is bad

Theory

  • two persons (comes from rally driver)
    • driver (with the keyboard, focused to the current problem)
    • navigator (looking more at the whole concept)
  • switching roles regulary

Why

  • less bugs
  • faster in development (problem solving)
  • continous knowledge exchange
  • tightest feedback loop you can get in programming (even unit tests take longer)
  • P (plan), D (do), C (check), A (act) - loop
  • communication
  • simplicity (doing simple things, because two people have to understand)
  • feedback
  • respect
  • courage
  • bring back fun into work

Principles

  • feedback
  • embracing change (also the guy which code is change would became less grumpy)
  • assuming simplicity
  • seven synergies
  • pair pressure (chance they get interrupted is become lower)
  • pair negotiation
  • pair courage
  • pair review
  • pair debugging
  • pair learning
  • pair t(h)rust

Seven Habits of Effective Pair Programmers

  • take breaks (five minute breaks after 30 minutes)
    • take a look at "pomodoros" (5 up to 7 pomodoros is a full day work)
  • practice humility
  • be confident
  • communicate
  • listen
  • be a teamplayer
  • compromise vs standing firm
  • introverts vs extraverts / introversion vs extraversion
  • skill
    • shu-beginner (repeat presented action)
    • ha-intermediate (start break the rules/make innovations)
    • ri-expert (do not care about the rules)
    • do "shu" and "shu" - easy up starting into things
    • do "shu" and "ha" - create another master
    • do "shu" and "ri" - kickstart the shu
    • do "ha" and "ha" - biggest bang for the buck
    • do "ha" and "ri" - create another expert
    • do "ri" and "ri" - solve big problems

Type of Pairs

  • everybody pairs with everybody once in a time - good for knowledge sharing
  • pair hinging - do a user story together
  • test first pairing - implement, make the test red, switch and replay
  • stakeholder pairing - explain the stakeholder your code or the flow
  • newbie pairing - pair a newbie to a experienced one and finish a user story
  • pair bugfixing
  • pair release
  • write userstories/requirements as pairs
  • coding dojos - navigator and driver, audience can give feedback

To The Critics

  • knowledge iceberg (small explicit, tacit is the big part)
  • bug fixing cost (small: requirements, design, code, test, productiom :big)
  • flow state is established easily
  • groupflow
  • teamwork

Translate to de es fr it pt ja

version 1.1.0 of zend framework 2 locator generator released

I happy to announce the release of 1.1.0 of bazzlines zend framework 2 locator generator module for php. Important changes are:

  • prefixed console commands with "net_bazzline" to not pollute the available command environment
Translate to de es fr it pt ja

version 1.0.1 of zend framework 2 locator generator released

I happy to announce the release of 1.0.1 of bazzlines zend framework 2 locator generator module for php. Important changes are:

  • fixed links in readme
  • fixed namespace issue in test
  • added usage of zf console helper
  • updated dependencies
  • updated usage
Translate to de es fr it pt ja

version 1.0.1 of zend framework 2 console helper released

I happy to announce the release of 1.0.1 of bazzlines zend framework 2 console helper module for php. Important changes are:

  • added example code output
  • added apigen
  • moved to usage of "Zend\Mvc\Controller\AbstractConsoleController"
Translate to de es fr it pt ja

version 1.0.0 of zend framework 2 console helper released

I happy to announce the release of 1.0.0 of bazzlines zend framework 2 console helper module for php.
This module should easy up implementing console commands supporting POSIX Signal Handling.
Furthermore, there are some simple but useful methods implemented:

  • getConsole()
  • getParameter($name)
  • getRequest()
  • hasBooleanParameter($shortName = '', $longName = '')
  • hasParameter($name)
  • throwExceptionIfNotCalledInsideAnCliEnvironment()

How can I use it?


namespace MyModule\Controller\Console;

use Exception;

class IndexController extends AbstractConsoleController { public function indexAction() { try { $this->throwExceptionIfNotCalledInsideAnCliEnvironment();

        $this->attachSignalHandler($this);

        //some example items
        //  simple think about a lot of items that indicates longer
        //  processing runtime
        $items = array('one', 'two', 'three', 'four');

        //use implemented method to react on signal handling
        $this->processItems(
            $items,             //big list of items
            $this,              //current object
            'processItem',      //method that should be called for each item
            $arguments = array( //additional arguments for method 'processItem' (if needed)
                'foo',
                'bar'
            )
        );
    } catch (Exception $exception) {
        $this->handleException($exception);
    }
}

/**
 * must be protected since it will be called from the parent
 *
 * @param string $item
 * @param string $stringOne
 * @param string $stringTwo
 */
protected function processItem($item, $stringOne, $stringTwo)
{
    $console = $this->getConsole();
    $console->writeLine(
        'this is item "' . $item .
        '" with string one "' . $stringOne . '"' .
        '" and string two "' . $stringTwo . '"'
    );
}

/**
 * @return boolean
 */
private function beVerbose()
{
    return $this->hasBooleanParameter('v', 'verbose');
}

}

How can I install it?

with packagist


composer require netbazzline/zfconsolehelper:dev-master

manuel


mkdir -p vendor/netbazzline/zfconsolehelper
cd vendor/netbazzline/zfconsolehelper
git clone https://github.com/zfconsole_helper
Translate to de es fr it pt ja

version 1.0.0 of zend framework 2 locator generator released

I happy to announce the release of 1.0.0 of bazzlines zend framework 2 locator generator module for php.
This module should easy up the usage of the locator generator component in the zend framework 2 in a zend framework 2 application.

How ca I use it?

generate one locator

php public/index.php locator generate

generate all available locators

php public/index.php locator generate

How can I install it?

with packagist


composer require netbazzline/zflocatorgenerator:dev-master

manuel


mkdir -p vendor/netbazzline/zflocatorgenerator
cd vendor/netbazzline/zflocatorgenerator
git clone https://github.com/zflocator_generator
Translate to de es fr it pt ja

Zend Framework 2 - Use Own View Helpers In A Controller

Assuming you had created your view helper called "MyViewHelper", placed in in "Application\src\Application\View\Helper" and added it as "invokable" in your "module.config.php" (section "viewhelpers" => "invokables").

After adding it to your "module.config.php", you can use it in your templates and everything is working as expected.
But what happens when you need that special view helper in your controller?

First idea would be to code something like the following lines in your controller.

$this->getServiceLocator()->get('viewhelpermanager')->get('MyViewHelper');

To bad, this won't work. Do you want to debug it? just add the following line at the beginning of "AbstractPluginManager::get()" and search for your "MyViewHelper" call.
echo varexport(array('name'=>$name, 'hasName' => $this->has($name), 'autoloadAddInvokableClass' => $this->autoAddInvokableClass, 'classexists'=>classexists($name)), true);

"class_exists" will return a false since your alias is not available at this point. How to solve this problem? Simple adapt your view helper call the following way.
$this->getServiceLocator()->get('viewhelpermanager')->get('\Application\View\Helper\MyViewHelper');

Translate to de es fr it pt ja

zend framework 2 (zf2) - where to find the default manager config key names

For exampe, you want to add your own controller plugin in the module.config, do you know the key name out of the box? Me neither, but i know where to look.
Open the ModuleManagerFactory and serch for view_helpers to get the spot where and how the configuration array key names are defined.
After this, the adding of your controller plugin is a solveable task :-).

Translate to de es fr it pt ja

php - zend framework 2.1 released

The zend framework 2 girls and guys (hopefully there are some girls) have released their first minor update called 2.1.0. Congratulations from my side to you guys.

While reading the release notes my face starts smiling when i've reached the "new tooling sections". Why? Because of the following entries.

- Skeleton application creation - Module creation within a skeleton - Autoloader classmap creation - ZF2 installation to a directory

I can't wait to play around with that. There is also a great looking howto out there in the web.

Also quite exciting:

New Zend\Permissions\Rbac component, providing Role-Based Authorization Controls. These complement our existing Zend\Permissions\Acl component, providing another mechanism for providing authorization for your applications. We have Kyle Spraggs to thank for this addition.

Translate to de es fr it pt ja

howto - zend framework 2 - form multilingual error messages and labels

Since the first time working with the new zend framework 2 form elements, i like it. Everybody who had the pleasure to deal with the form class from zend framework 1 will agree on that. But after a little bit of playing around with it, i had to build a form that works with multiple languages and has a lot of mandatory fields. Since you are injecting a filterclass with validators into the form, you have to create the error message inside the filter class and like:

//part of a form filter constructor $this->add( array( 'name' => 'name', 'filters' => array( array( 'name' => 'StringTrim' ) ), 'validators' => array( array( 'name' => 'NotEmpty', 'options' => array( 'messages' => array( \Zend\Validator\NotEmpty::IS_EMPTY => 'I am the error message that should be multilingual.' ) ) ) ) ) );
So my first idea was to inject a translator. Since you are using a "MyMagicFormFactory" to create the form, you can easily inject the translator (or the servliceLocator if you want to). But after a few thoughts, i figured out that the error message itself is totally wrong on that place, for my point of view. I thing a form as well as a filter is not responsible for a human readable error message. Thats why i moved/reset the definition of the error message and handle it in the template. Of course, i am also using the translator but now only in the view layer. By the way, i will deal the same way with the labels for each form element.

So the simple question is how to deal with it?

To keep it simple, i will not use the translator inside the following example. Assuming you a form with a input field for an email address. You can deal with it the following way.

<?php echo $this->form()->openTag($this->form); ?> <dl> <dt> <!-- we don't use the method ->getOption('lable') since we want to deal the multiple languages inside the template --> Your mail address </dt> <dd> <?php echo $this->formEmail($this->form->get('email));

$messages = $this->form->get('from')->getMessages();
//take a look inside the $messages since it is an array with keys like 'isEmpty'
// if you want to create error messages by key, thats the way you can handle this.
if (!empty($messages)) {
    echo '&lt;label for="from" class="error">Please insert a valid email address.&lt;/lable>';
}
?>
&lt;/dd>

</dl>

Enjoy working with zend framework 2 :-).

Translate to de es fr it pt ja