Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Thursday, June 12, 2014

Install APCu on Windows

Assumptions

-I assume that you know what is APC - Alternative PHP cache 
-You want to install APCu because APC is not compatible anymore with PHP 5.5.x
-You want to install APCu for wamp, xampp. Mostly windows web development platforms for PHP

Instructions

Pre: All directory locations might be different for you depending on your wamp installation folder and your PHP/apache versions.

1. Go to http://pecl.php.net/package/APCu, there is a table with available releases
2.Choose whatever release suits you better(I chose 4.0.5 DLL)  
3. Choose package from DLL list, depending on what Windows you are using(32 bits/64 bits) and PHP version. In my case I chose 5.5 Thread Safe (TS) x86
4. Unzip the archive, copy php_apcu.dll in C:\wamp\bin\php\php5.5.12\ext.
5. Go to C:\wamp\bin\apache\apache2.4.9\bin open php.ini  and add the following lines(I just added them at the end of the file):
[apcu]
extension="C:\wamp\bin\php\php5.5.12\ext\php_apcu.dll"
apc.enabled=1
apc.shm_size=32M
apc.ttl=7200
apc.enable_cli=1
apc.serializer=php

This are recommended configurations located in INSTALL file from the php_apcu archive, excepting the location of the DLL file.

6. Restart wamp
7. Go to http://localhost/phpinfo.php and check if apcu configuration table appears and apcu is enabled
8. If you also want to use apcu for PHP CLI then you only need to add in C:\wamp\bin\php\php5.5.12\bin\php.ini the config lines you added at step 5 in apache's php.ini.

The end!

Now you should be ready to start developing faster applications! I hope this helped everyone out there who did not find a tutorial on how to install APCu for windows. I also encourage you to leave me some feedback!

Robert Rusu

Monday, January 27, 2014

SymfonyLive Portland 2013 - Alexander Mols - Taking caching to the next ...



I recommend you to watch the video because Alexander presented a lot of tips and explained a lot of things regarding caching.
Topics discussed:

  1. Caching for Routing, Container component of Symfony2
  2. Caching in Twig
  3. Doctrine Caching
  4. Varnish
  5. Tricks to prevent making a request to the Symfony2app for misc stuff like showing an html edit anchor

Sunday, January 26, 2014

Wordpress Auto Update Feature

CodeIgniter is Out and Laravel is In!



While working on some projects developed codeigniter more than a year ago I also had issues with the session component not working properly on IE, not sure if they solved that issue. Too bad that codeigniter framework is not developed anymore because as far as I know there are a lot of PHP web applications using codeigniter.

Monday, October 7, 2013

Installing phpunit/PHP_Timer issue

After uninstalling phpunit/PHP_Timer and trying to install another version I was getting the message
No releases available for package "pear.phpunit.de/PHP_Timer" install failed
But I did not have PHP_Timer installed at all, the solution for this was to run
pear clear-cache
After that command to install phpunit/PHP_Timer pear install phpunit/PHP_Timer ran successfully!

Saturday, August 24, 2013

Symfony2 routing tip

Symfony2 routing tip

Did you ever needed to make the default value to NULL of a routing parameter when using XML for symfony2?
Here is a sample configuration
<route id="acme_user_show" pattern="/{id}">
    <default key="_controller">AcmeUserBundle:User:show</default>
    <default key="id" xsi:nil="true" />
</route>

Saturday, July 6, 2013

Continuous Integration In PHP

Here is a nice article I found about continuous integration in PHP wrote by Eric Hogue. He covered some aspects and some useful tools like:


  1. PHPUnit
  2. PHP CodeSniffer
  3. PHP Depend
  4. PHP Mess Detector
  5. PHP Dead Code Detector
  6. Jenkins
Most of this tools were written by Sebastian Bergmann. Great work!

I use PHPUnit and code coverage tools and I must say its a great experience, and its very useful! I am planning to use the new tools I discovered on my next project. 

I recommend them to any PHP programmer, even if some of you are not programming in PHP I am sure that there are similar tools for you too. For example JUnit for Java developers.

Thursday, July 5, 2012

Including php files

Let's say that you have some functions that you want to use for a project of yours. If you copy paste the functions in all files where you need then when you want to change the way a function work you need to change it in all places. This changes are a lost of time and you will surely not modify it in all files so bugs may appear. The solution is to include php files using include and require methods that PHP provides us.

Using include

You can include a file like this:
include "functions.php"
Using this statement requires that the file functions.php must be in the same folder with the file in which you are including your functions. You can use relative or full path to the file like this:

include "usr/local/apache/htdocs/includes/functions.php"
For Unix/Linux/Mac path

For Windows the include statement might look like this:
include "c:\phpfunctions\functions.php"

The problem with include is that every time the PHP processor finds an include statement is that it will load the file in again. This takes up more memory than is necessary and is slow and inefficient. The other problem is that loading the file again will make functions to be redefined, which is not allowed, and will generate an error message.

Using include_once

If you are using include_once then the processor will check if the file is not already loaded and it will load it if it is not loaded. You can use it like this:
include_once "functions.php"

The problems with include and include_once is that if the file does not exist then the command will simply get ignored. Maybe some of those functions are needed for the website to work then you will get a lot of errors, maybe some errors like function not found. The solution is the require command.

Using require

require "functions.php"
Using require instead of include will return an error and halt the program execution if it cannot locate the requested file. This will help you if you misplaced a file or you got the file name wrong. But the story is the same, require will reload the file each time, the problems of this matter are the same as when using include command. The final and best solution is require_once command.

Using require_once

require_once "functions.php"
Like include_once this will only ever load in a single copy of the file, no matter how often that file is required. But, unlike include, it will also generate an error if it can not find the requested file.


Reference:

Friday, June 22, 2012

Why use a PHP framework?

There are several reasons to use a framework instead not using one. The framework that you are using can be one that is open source or your company/team developed for future projects. Learning how to use a PHP framework(or any other framework developed for other languages) can take time depending on multiple factors like documentation, community, practices and patterns that it uses. But it will worth your time because when developing web applications using that framework it will be faster than not using one. 

For example Codeigniter is a lightweight framework that it is easily to use and learn, I mean really easy to learn it. You can start developing a website after a few hours you have downloaded it. But if you have to work on a large project then you should use for example Zend or Symfony2 because these frameworks have more components available to help you with different tasks.

Easier to understand someone else code

 Firstly if you using a framework then other developers who uses it will understand better your code. If developers understand better the code then they will easily extend, fix bugs or use what you wrote. Let's say that you work at a small company in a team of web developers and one of your team member gets married then he has no time to finish the project on which he was working on. Another team member will easily continue his work if he uses the same framework and if the team has a certain coding standards.

If you have some experience with a framework then you will get a job easier because a lot of companies use at least one framework. The most popular frameworks are Symfony2, Zend, Codeigniter, CakePHP. Here is a comparison.

Built in classes that help you

The second advantage of a framework is that you can reuse classes that helps you to get your job done faster. For example the framework can have a database layer that is easier to use for connecting to a database, maybe the framework has a class that helps you to write queries without writing any sql. Of course that in larger projects you must know how to write complicated queries.

Another example is Zend, this framework has a lot of modules that help you to work with different APIs. Zend has a module that helps you to work with Amazon Service. Here is a piece of code example:

$amazon = new Zend_Service_Amazon('AMAZON_API_KEY', 'US',  
'AMAZON_SECRET_KEY');
$results = $amazon->itemSearch(array(
    'SearchIndex' => 'Books',
    'Keywords' => 'php',
    'AssociateTag' => 'yourtaghere'
));

Your web application would be more secure

Another advantage is that a lot of PHP frameworks have built-in security. I am not saying that you should leave the framework to take care of all the ways that someone could break your website but your web application would be more secure if you are using a framework.

Build in caching

Most frameworks have build in caching components that will make your web application faster. This components give you the power to control caching in different ways like timing and other things. Here is an article about Symfony2 caching component.

Separating your logic in your web application

For example if you are using a MVC framework and you are separating the logic of application in the three major parts: views, controllers and models then it will be faster to develop, test it, refactor it and understand it. The views should not contain any logic, it should only present data to the user. The controller must receive a request and return an response. And most importantly the models should contain your logic of the application and your database queries. If do not organize your files and your code properly then your project will become a mess and it will be hard to debug it, to extend it and to reuse that code. It will become a spaghetti code!

Conclusion

Learning a php framework can take time depending on which you are learning but the productivity will grow. Frameworks have a lot of components that will ease your work. Inevitably you will learn to separate your files and code in a way that makes sense to you and the others who use the same framework. Almost all PHP frameworks are Object oriented so all of them use the best OOP Patterns to solve common problems. If you want to start building your own MVC framework then you should follow this tutorials.


Saturday, June 16, 2012

Introduction to Object-oriented programming with PHP

I found a great slideshow consisting of 122 slides in which Marcus Börger made an introduction to Object-oriented programming with PHP. The presentation was made at a PHP Conference in Quebec in 2007 and the author pointed out the next topics:
  1. What is OOP?
  2. PHP and OOP
  3. Exceptions
  4. Iterators
  5. Reflection
  6. Patterns
 I think this will help you understand better the Object Oriented programming in PHP even if the presentation was made in 2007.

Thursday, June 14, 2012

20 advices when starting to learn PHP

Here is a great article to read if you are just starting to learn php. The presented advices are:

  1.  Program as often as you possibly can
  2. Get familiar with the PHP manual
  3. Take advantages of the huge online PHP Community
  4. Don't put off the best practices for later
  5. Don't put off the best practices for later(to be sure you saw this)
  6. Make code self-documenting
  7. Add a comment to anything you had to think about
  8. Learn Docblock and use it!
  9. Don't be too hardcore to use an IDE
  10. Group common code into functions
  11. Group related functions into classes
  12. Use constants, not globals
  13. Don't be afraid to use includes
  14. Don't obsess over performance
  15. Avoid Marrying HTML to your scripts
  16. Try to use at least one unfamiliar concept in every project
  17. Don't be too proud to change
  18. Validate
  19. Whitelists instead of blacklists
  20. Learn to count like a computer
Please read the article to understand better each advice. Thank you Jason Lengstorf at http://net.tutsplus.com .

Monday, June 11, 2012

Sonata AdminBundle: How to create a custom field

I wanted to create a custom field that is not in the database for the listFields so I searched the web how do it. Here is how I have done it:


class Entity 
{
    ...
    //custom getter
    public function getFullName()
    {
        return $this->getFirstName() . ' ' . $this->getLastName();
    }
}


In your EntityAdmin:

 protected function configureListFields(ListMapper $listMapper)
    {
        $listMapper
           ->add('fullName', 'doctrine_orm_string')
            ->add('_action', 'actions', array(
                'actions' => array(
                    'view' => array(),
                    'edit' => array(),
                    'delete' => array(),
                )
            ))
        ;
    }

Sunday, June 10, 2012

Sonata Admin Bundle error:configureShowFields

If you get this two errors:
[2/2] FileLoaderLoadException: Cannot import resource "C:\wamp\www\project\app/config\." from "C:\wamp\www\project\app/config\routing.yml".  -+

[1/2] ErrorException: Runtime Notice: Declaration of Company\NameBundle\Admin\EntityAdmin::configureShowFields() should be compatible with that of Sonata\AdminBundle\Admin\Admin::configureShowFields() in C:\wamp\www\havefun\src\Company\NameBundle\Admin\EntityAdmin.php line 84  -

Check if you included the ShowMapper class like this:
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Show\ShowMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Validator\ErrorElement;
use Sonata\AdminBundle\Form\FormMapper;

protected function configureShowFields(ShowMapper $showMapper)
    {
        $showMapper
            ->add('name')
            ->add('email')
        ;
    }

Saturday, June 9, 2012

SonataAdminBundle weird breadcrumbs

If you installed SonataAdminBundle and your breadcrumbs look like this 0/1/ then the solution to this problem is to reinstall the KnpMenuBundle, but the 1.1.0 version, you can find it on git . Add this to your deps file:
[MenuBundle]
git=https://github.com/KnpLabs/KnpMenuBundle.git
target=/bundles/Knp/Bundle/MenuBundle
version=v1.1.0

[KnpMenu]
git=https://github.com/KnpLabs/KnpMenu.git
target=/knp/menu
version=v1.1.1
  
But before running the command  php bin/vendors install --reinstall  make sure you comment the
'Knp\Menu'   => __DIR__.'/../vendor/knp/menu/src',
    'Knp\Bundle' => __DIR__.'/../vendor/bundles',

in the app/autoload.php file

and comment  the
new Knp\Bundle\MenuBundle\KnpMenuBundle(),

line in the app/AppKernel.php file

Also you might have to comment the:
   lines of code in app/config
      sonata_admin:
    title:      HungryCoders
    title_logo: bundles/sonataadmin/logo_title.png
    templates:
        # default global templates
        layout:  SonataAdminBundle::standard_layout.html.twig
        ajax:    SonataAdminBundle::ajax_layout.html.twig

        # default actions templates, should extend a global templates
        list:    SonataAdminBundle:CRUD:list.html.twig
        show:    SonataAdminBundle:CRUD:show.html.twig
        edit:    SonataAdminBundle:CRUD:edit.html.twig
    dashboard:
        blocks:
            # display a dashboard block
            - { position: left, type: sonata.admin.block.admin_list }

...


services:           
    sonata.admin.product:
        class: Demo\TestBundle\Admin\ProductAdmin
        tags:
            - { name: sonata.admin, manager_type: orm, group: demo, label: Products }
        arguments: [null, Demo\TestBundle\Entity\Product, DemoTestBundle:ProductAdmin]

Now you can run the command to install the vendors, and UnComment the code in app/autoload.php, app/AppKernel.php and app/config/config.yml. Now your breadcrumb should look good.

Monday, June 4, 2012

Event Listener Example

Here is an event listener example. I made a little game using Symfony2 framework and I needed to check if the user chose a hero(character) to play before trying to make some actions like view inventory etc.
src/HungryCoders/HeroGameBundle/EventListener/BeforeControllerListener.php:
<?php
namespace HungryCoders\HeroGameBundle\EventListener;

use Symfony\Component\HttpKernel\Event\FilterControllerEvent;

class BeforeControllerListener
{
  
    protected $session;
    protected $resolver;
  
  
    public function __construct($session, $resolver)
    {
        $this->session = $session;
        $this->resolver = $resolver;
    }
  
    /**
     * This is used to check if the user that wants to access some hero game controller
     * chose a hero to play with
     */
    public function onKernelController(FilterControllerEvent $event)
    {
        $controller = $event->getController();
      

        if (!is_array($controller)) {
            // not a object but a different kind of callable. Do nothing
            return;
        }
        $controller = $event->getController();
        $controllerObject = $controller[0];
      
     
        if ($controllerObject instanceOf \HungryCoders\HeroGameBundle\Controller\BattleController
        ||  $controllerObject instanceOf \HungryCoders\HeroGameBundle\Controller\HeroController
        ||  $controllerObject instanceOf \HungryCoders\HeroGameBundle\Controller\InventoryController
        ||  $controllerObject instanceOf \HungryCoders\HeroGameBundle\Controller\TownController
        )
        {
            if ($this->session->get('heroGameHeroId') === null) {
              
                $this->session->setFlash('heroGame.mustChooseAHero', 'You must choose a hero to play');
              
                //a way to create a new response without any redirect just create a response using a controller action
                $request = new \Symfony\Component\HttpFoundation\Request();
                $request->attributes->set('_controller', 'HungryCodersHeroGameBundle:HeroAccess:dashboard');
                $event->setController($this->resolver->getController($request));
            }
        }
    }
}


src/HungryCoders/HeroGameBundle/Resources/config/services.yml
parameters:
    heroGame.battle.maxRounds: 5
    heroGame.attack.rangeLevels: 5

services:
    beforeController.listener:
        class: HungryCoders\HeroGameBundle\EventListener\BeforeControllerListener
        arguments: [ @session, @controller_resolver]
        tags:
            - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }

Great PHP OOP video tutorials

If you want learn about PHP Object Oriented Programming than I strongly suggest to watch these video tutorials at http://jream.com/learning/videos/php-oop . After you watched them if you want to learn about MVC framework you can start making your own framwork  by following the video tutorials that are available at the same url. I hope this helped you!

What is Symfony2?

I found a great article wrote by Fabien Potencier on his website the topics that he reached are:
  1. What is Symfony2?
  2. Is Symfony2 an MVC framework?
  3. Why does it matter?
  4. Why Symfony2
  5. The Symfony2 Components
I really encourage you to read his post! Thank you Fabien Potencier!

Monday, May 21, 2012

Installing Sonata Bundle Error

If you get the next error when using Sonata Admin Bundle you should use the Sonata Admin Bundle 2.0 branch.

Fatal error: Declaration of Sonata\AdminBundle\Form\Extension\Field\Type\FormTypeFieldExtension::getDefaultOptions() must be compatible with that of Symfony\Component\Form\FormTypeExtensionInterface::getDefaultOptions() in /var/www/pulpower.spotymedia.com/vendor/bundles/Sonata/AdminBundle/Form/Extension/Field/Type/FormTypeFieldExtension.php on line 186

 Clear the deps file and copy the next code

[SonataAdminBundle]
    git=git://github.com/sonata-project/SonataAdminBundle.git
    target=/bundles/Sonata/AdminBundle
    version=origin/2.0

run the command php bin/vendors install -reinstall

Now everything should work.

https://github.com/sonata-project/SonataAdminBundle/issues/679

Sunday, May 20, 2012

Installing SonataAdminBundle Error

If you get the next error when installing SonataAlbumBundle:
The child node "default_contexts" at path "sonata_block" must be configured.

Then you should include this code in your app/config/config.yml file
 # app/config/config.yml
sonata_block:
    default_contexts: [cms]
    blocks:
        sonata.admin.block.admin_list:
            contexts:   [admin]

        #sonata.admin_doctrine_orm.block.audit:
        #    contexts:   [admin]

        sonata.block.service.text:
        sonata.block.service.action:
        sonata.block.service.rss:

        # Some specific block from the SonataMediaBundle
        #sonata.media.block.media:
        #sonata.media.block.gallery:
        #sonata.media.block.feature_media: