Tag php

Read about the posts of tag php

Docker is a new way to use virtual machines (someone expert that read this, not hates me, it’s a way to show what it is). Docker represents an easy step to install services on our machine without installing it. This means, is like a virtual machine using your own hardware instead of virtualizing it and where you can install things. It’s complex to explain because Docker is a half-path between your own computer and Virtual Machine.

The best way to understand what is and why use it is creates a basic example. We are web developers, the best is to create an Apache Image with PHP and execute some code.

Install Docker

Let’s try it. First, install Docker, this is important. If you don’t install the examples in this article couldn’t work!

You can download a copy of Docker here: Docker Engine installation

Install and …. continue.

Now it’s time to create containers. Docker has containers, a container is a service installed and you can pile containers to add more services. Let’s go to work and stop rare words!!

Create Image

This tutorial talks about creating an image that you can use and reuse. Time to create. Move to a new folder and create a file called Dockerfile and add the next lines:

It’s a two-line file. Simple instructions:

  • FROM chialab/php:5.6-apache: tell what docker image you want to use. I’m choosing chialab images because have a lot of libraries installed. You can choose another one if you want. Feel free, I always use it because have all I need for development. Search images here: Hub docker
  • ENV APACHE_LOG_DIR /var/www/html : Tell image internal environment variable.

Time to build. We have a simple Dockerfile and now need to build our image, open the terminal window and move to the Dockerfile folder and execute the command:

We built an apache image, execute the next command to see your images:

Use Image

Now it’s time to use it. Then, create an index.php page with phpinfo() instructions.

Only one more step and we are done. Time to execute the magic command:

What’s the meaning of commands?

  • docker run: tells to execute image
  • -v: is for mount volumes. I’m telling that folder $PWD (it’s system variable for actual folder) maps to /var/www/html inside image
  • -p: map port 80 on our computer to port 80 in an image.
  • apache: Docker image name

If you aren’t using Mac Os X or any Linux based OS you can change $PWD for another folder:

And finally, open your browser and write https://localhost You will see a phpinfo() information:

docker-phpinfo

You are running a web server now with apache. Thanks to docker it’s easy to create environments without installing any software on our computers.

Git Workflow or GitFlow it’s a development model to work with code and git. We use extended in our code to make conflicts between developers less than possible. The reality is that Git Workflow is branch management for organizing code and developers. There are many ways you can manage branches, we only use 2 or 3 at least, but you can combine them (we do) into more possibilities.

 

If you don’t know about Git or Branch you can read our previous post:

 

Basic Workflow

Actually, a lot of developers works alone and git give them the security of know that their code is well organized in a lot of commits. If you are a little bit organized you will do push for every functionality, for example, add a delete button to code, and you know every commit is a function. Sometimes no, simply you are developing and every time you remember to do a commit. This other way too, because you are in fast mode and can’t stop to think some details. Anyway, imagine that you need help and someone comes to help with development tasks. You give them access to git and he/she clone code and begin the work. The most normal is both developers work in the same branch, master.

Let we see what happens. Two developers, Barbara and Victor. One repository with one branch. Victor begins to work:

Then create a basic PHP with some HTML inside:

(yes, I forgot one p tag)

Now I add a file and commit push:

Then Barbara comes to work and Victor give access to her (we use the same user in different folders, that is similar):

Yeah! we have now the same repo in two folders, it’s like Victor and Barbara works now. Then, Barbara begins to develop and add a new line to index.php:

She commits and pushes:

And like a good coworker, she tells to Victor and he pulls changes:

Then Victor review the changes editing index.php. Victor sees p tag mistake and decide to change the line and something else:

He commits and pushes:

And Barbara, see the same mistake and make similar changes:

And …

.. Fail. What the hell!? both of them changes the same lines and Barbara, second to push have a real problem. But isn’t the big problem, she tries to pull:

Git found a big conflict because changed lines are the same in two repositories. And Barbara decides to open index.php to see what happened:

Oh!! it’s terrible, a lot of awful code is new in the file. Ok, let’s see what we can do. Git divides conflicts into two areas, this is the area corresponding to code in our own machine repository:

And the other part is corresponding to the server repository:

Now Barbara needs to clean code deciding what part is correct and what isn’t (you can use some automatic tools, but that isn’t the purpose of this article). Finally, Barbara cleans the code:

And now we need to commit and push again:

The difficulty isn’t to modify 2 lines and decide what line is correct. Imagine one file with thousands of code lines and three or four developers. Or Worst, ten files with thousands of modifying code. The poor guy that gets merge problems has all loose day looking for the code problems.

 

Git Workflows Type

Now we saw the big problem working with the same repository and one branch. We discuss now different ways to avoid problems with different types of workflows.

Feature Branch Workflow

After the hell of Basic Workflow or Centralized Workflow, it’s easy to think to leave this kind of work. It’s a hell, a real hell. I participate in a 4 members team, a lot of years ago, working with Centralized Workflow and was really hell. Entire weeks loses merging code, it was a nightmare.

All of my problems could have been solved used this simple way of work. Making single Branch for every feature. The idea is simple, you make a new branch for every feature you need to implement.

Let’s explain and continue the Barbara and Victor history :)

After Victor review the code decides to move to Feature Branch Workflow then he decides to create two branches, one for add code and another for add HTML:

With git checkout -b new branch can create a new branch and change to them, the important is -b option that means “create a new branch. Now we are in feature-HTML and we need to add some HTML file to our index.php, Barbara begins their work:

We remove the commented PHP line and add a new one at the end. Now it’s time to commit and push.

Now time for Victor, he needs to add some code, first we change the branch and begin codification:

We have actually 3 branches with different codes and need this code altogether. Like Victor is a master developer, he controls now the merge ad code, first integrates the feature-code branch:

See the process, first change branch to master: git checkout master
Then pull code from the server, we need to have the latest code: git pull origin master
Then pull feature-code branch: git pull origin feature-code
Now we have merged code, we could do the same with git merge feature-code
After code merged we need to push: git push origin master

Now we can do the same process with the other branch:

It’s the same error as before, but here resides the difference: Victor, in this case, are Team Lead, knows what happens with code and how to resolve conflicts, indifferent to Barbara that just arrives at the project. Too we introduce new command: git mergetool

Maybe you haven’t configured the repository with any tool, but your system won’t let you alone:

I’m assuming that open diff is there and just hitting enter:

opendiff tool

This looks better than edit the directly file in the editor. The tool will be different depending on your Operating System, my case is Mac OS X then this is the default tool. Just arrange some lines and finish.

And:

Yes, we have completed our Feature Branch Workflow. If you use Bitbucket web page or Github web page for make merges is more easy and intuitive. I will talk about merge with bitbucket or GitHub in another post.

User Branch Workflow

User Branch development isn’t recommended for any. Just is to create a branch for every person in your team and all of them do merges to master. It’s also highly recommended to merge from the master te person branch. I worked before with this system in a big company with a little crazy Lead Developer. It’s not a bad idea if you are small teams (two persons), but with big teams it’s insane.

No examples here, just wanted to comment on the option.

GitFlow

GitFlow borns with nvie post.

He explains a way to organize branches to work. It’s easy, it’s organized, it’s cool, it’s fantastic, terrific! Nvie divides work into two main branches and supporting branches. Let’s see how it works.

Main Branches

After you init your repository and add some code you need to add one branch called to develop. You will have two main branches:

  • master: master branch will be the production branch. The code here is the same as will be on the production server. Every time you merge code from developing to here means you need to upload code (or push-pull) to production.
  • develop: this is the main branch where code comes to test before production. No one uses this branch, the code only come from merges.

It’s easy to understand. The Master branch is production, develop is where we test code. When you think the code is correct in development it’s time to merge to master and upload to production.

Supporting Branches

Are three types of auxiliary branches:

  • Feature Branches: Every time you need to make a new feature you can create a feature branch. You can name wherever you want, but in EBAVS/ we name with feature-* convention:

Is important to use –no-ff option. This means no fast forward. Fast Forward loses history when you do merge. Is important to maintain history.

  • Releases Branches: Releases Branches is where features go, you can prepare here a production release. They born in develop branch and You can name with a minor or revision number. After you finish release, you can merge with the master branch directly, create a tag with revision, merge release into develop and finally remove the release branch:

  • Hotfix Branches: Hotfix branches are branches that born from the master branch because code needs to fix urgently. After fixing the code you can merge again to master and develop. Naming is with revision number:

 

Finally

This tool is powerful, you can use it to organize your code or to ensure that you can develop in a quick and safe way. But if you use it in a bad way could convert into pain. GitFlow it’s a good workflow we can use actually. Maybe are others, but this one fits perfectly in our day to day coding.

This article is dedicated to Alex, that asks me how to create a basic CRUD from a database without development, this is called Scaffolding.

For me, Scaffolding is one of the most amazing techniques that people don’t want to use. Exist a major reason, that reason is every time someone accesses the URL and execute the code, a huge process begins asking for the database and constructing the CRUD from zero.

Exist a lot of frameworks with Scaffolding in PHP, but I prefer CakePHP by its simplicity. Other languages like Python with Django and Flask or Ruby On Rails have their own mini scaffolding.

A little Terminology

Actually, the last version of CakePHP doesn’t support Scaffolding, they remove it in the 2.5 version (actually the last version of CakePHP is 3.3).

Before to begin I want to explain some of the vocabularies here:

  • CRUD: means CReate Update Delete. Actually when developers talk about CRUD refer to the pages needed to list records from a database, form to create new records and form to update records.
  • Scaffolding: Technique that creates CRUD list and forms on the fly and shows it.

Ok, continue explaining the difference between the two main techniques regarding this. The best of both is CRUD generation. CRUD Generation executes one code that explores the database and generates the PHP files needed to access a database. Scaffolding does something similar, explores database and create CRUD on the fly. This is the reason that needs a lot of resources.

If you have a consistent database and don’t need to change anything I recommend that you use some of the CRUD generators. Two of the best for me:

We need Data

Now I want to begin our amazing scaffolding project. First of all, I need to create a database. I will begin to create 2 tables. One of the articles and others from categories of articles. Something simple.

I followed the model convention name of CakePHP:

https://book.cakephp.org/2.0/en/getting-started/cakephp-conventions.html#model-and-database-conventions

I don’t want to enter to explain databases, I suppose that you can figure out how to create your own database and tables and connect to a server. Anyway, here the structure:

 

Install Cake

It’s time to install CakePHP. You can choose to download or use git. I prefer git but maybe you want to download:

Git

I create a directory and enter it and clone:

With -b ‘2.4.9’ in clone, we are telling that only want this branch or tag. If you look VERSION.txt of CakePHP you can see version:

Download

You also can download it directly from GitHub. Follow the next link and click the green button called Clone Or Download and then click Download ZIP. Decompress the file in a directory and continue.

Github Cake PHP

 

Try It

If you are using Apache in your environment, all works fine and you halt next step.

NGINX

In another hand, if you work with nginx you need to configure your server to make a good environment for CakePHP. Follow instructions in CakePHP Cookbook:

Book Cake PHP Installation

Trying

Then, if you load now your CakePHP URL you will see your first big-screen :)

screen-shot-2016-11-15-at-11-25-17

 

This is correct, CakePHP is telling us that all is correct but a database isn’t we need to write database config.

Configure Cake

First, we need to connect to a database. This means that we need to create a configuration file. We have one sample file in:

Rename it to

And open it, search for the next code and fill it with your data (is important that uncomment utf-8 if you use accents):

A configured database, the next step, begins the big and complex scaffolding code.

Creating Models

Now it’s time to create the models’ files to tell CakePHP what tables are involved. Create a file:

And write (or paste) the next code:

Save it and do the same with Articles:

And code:

It’s done, we have models.

 

Creating Controllers

It’s time to create Controllers. Controllers are files that control the execution of an application and ask models for data and send to views.  In CakePHP also are mapped to URLs. If you want to access to domain.tld/products you need to create a ProductsController. In our case, I want two URLs, one for Articles and the other for Categories. Create file:

And now the most complex and difficult to read code:

The property $scaffold is the most important, tell CakePHP that this controller is a Scaffolding controller.

Now for categories:

and code:

It’s done. Scaffolding it’s working. You need to access the domain.tld/articles and CakePHP does the work for you, scaffolding in action.

Scaffolding

Scaffolding List:

Scaffolding List

 

Scaffolding Edit:

Scaffolding Edit

You can browse for categories in the domain.tld/categories

Improvements

If you browse a little bit, you notice that category isn’t shown in Articles Scaffolding, only show ids. This is because the models need to know the relations between tables. Only change models to:

With $belongsTo and $hasMany properties, we tell to Cake the relation with tables. Remember that if you don’t follow conventions this relation won’t work. In Articles is important the existence of category_id, with another name the relation will be more complex. You can see relations here:

Book CakePHP Models

Finally, I show you how can use Scaffolding with CakePHP. But remember that this is hard work for servers if you use a lot of tables and users, and is better to use CRUD instead.

I recently spoke with a personal fan of PHP development. He had developed a page with Bootstrap and PHP, and things of life, we found a huge bug in the registration and user login. After talking a while with this person I realize that the guidelines or implementing rules were was still PHP 5.1 or PHP 5.2 (today we use PHP 5.6). Use functions mysql_ for the connection and query to the database, the PHP pages use pattern spaghetti (Spaghetti Code, POO absent, etc …
Worst of all, in the last year, I have seen a lot of this type of code. So we are working to changing this. One of the problems is how difficult it is nowadays to find reliable articles on Google. If we search something as normal as PHP database connect appears results like these:search for sql connection for development Check the first three results, they are obsolete PHP documentation. In PHP 5.5 marked as deprecated the mysql_ functions and PHP 5.6 does not work.
 The fourth result is a post that explains how to create a database connection (what we wanted!) but… in 2006. 9 years ago! When people – who want to start in the development’s world – find these results and followed them, please do not follow, unfollow them. I recommend the following guidelines, updated in 2015 that explain the current way of developing in PHP.
PHP The Right Way
PHP Best Practices
These guidelines will help you have a more solid foundation in development with PHP.