Thursday, 21 March 2019

Introduction to Yii

Yii is a PHP, MVC framework which has been built with performance in mind.

Creating a new project

Let's imagine I've created a yii-apps directory to put all my Yii tests in.
cd yii-apps
If I run the following :
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
I'm doing a number of things:

  • Using composer with the create-project command.
  • Adding the --prefer-dist option to the create-project command which will install packages from dist directory when available.
  • Adding the --stability=dev option, so that the app will be created as a piece of development rather than production. That can come later.
  • Creating the app using the 'Yii 2.0 Basic Application Template'. There are many application templates you can use. Some of them are written by 'yiisoft', the organisation which develops Yii itself.

Once installed, you can use the following command to see you application.
php yii serve
This would give you a URL such as http://localhost:8080/
Alternatively, if you already have a LAMP server running, you can use a URL like this in your browser:
http://localhost/test/yii-apps/basic/web/

How is it structured?

Yii applications are loaded using the following hierarchy:
Entry script -> Controller -> Actions

Yii Views are HTML with PHP. You can use helpers such as yii\helpers\Html and widgets such as yii\widgets\ActiveForm to create views

Yii models use the "active record pattern (methods)" to pull and push data, so in most cases you won't need to write queries.

You can use composer to perform tasks on your application such as create it, or add components.

composer.json handles all the components

config/web.php handles all the routing. Here, you can uncomment the urlManager section to handle pretty URLs.

controllers/SiteController.php is the default controller and contains a method call actionIndex(). This takes users to the index view residing at views/site/index.php. This is where the naming convention becomes obvious. Our controller is called SiteController.php and it corresponds to views/site.

web is the directory containing all the CSS and images etc.

vendor is the directory containing all the libraries.

A full description of the directory structure can be found at https://www.yiiframework.com/doc/guide/2.0/en/start-workflow

One final tip

Since PHP 7 came out you can require multiple namespace items as below:
use some\namespace\{ClassA, ClassB, ClassC as C};
use function some\namespace\{fn_a, fn_b, fn_c};
use const some\namespace\{ConstA, ConstB, ConstC};

Friday, 15 March 2019

JIRA, briefly

JIRA Project

JIRA 'Project' is the highest level container, and can be created from the JIRA homepage.
In JIRA the SCRUM workflow template is the default option when creating a new project.

Issues

An 'Issue' in JIRA is a single work item within a project. An issue can be created from the '+' button on the left of the screen from within a project.
An issue should take at least a few hours, but not more than 3 days.
Issue types are :

  • Stories
  • Tasks
  • Epics
  • Bugs

Stories

Stories are planned work for a specific feature, e.g. as a user I need to delete any element of a list.

Tasks

Tasks any other planned non-story work, e.g. create the new custom module table.
Unplanned work, e.g. Put '+44' at the beginning of UK phone numbers.

Epics

An epic is a collection of stories and tasks to achieve a noteworthy outcome. Sometimes it's a good idea to think of epics at the beginning of a project and fill them with stories and tasks as you get into the detail of a project.

Labels & Components

Labels and Components are tags applied to issues which allow you to filter issues.

Labels

Labels e.g. Front-end, back-end, red-team, blue-team.

Components

Components e.g. User profile module, machine learning engine.

Backlog

'Backlog' refers to the product backlog document in SCRUM. There is a Backlog link on the left of the JIRA screen within each project.
The backlog list in JIRA contains stories and tasks. You can use this list to priortise the work into sprint size blocks.
The backlog also contains epics which you can drag and drop into priority order. You can also then drag stories and tasks into those epics.
The backlog also contains an 'All issues' section from which you can see all stories and tasks which are colour coded by the epics you have prioritised them to.
The All issues list within the backlog also contains a list of sprints. You can drag and drop stories and tasks into sprints by priority order. At the bottom of each spint list is an estimate of how long the combined issues should take. This should help you stay within sprint period i.e. normally 2 weeks.

Story points

Story points are a relative measure of complexity, e.g. 13 is harder than 5. Perhaps early on, it's a good idea to give a 2-3 hour issue a story point of 1, whereas an issue taking 3 days could get a story point of 13.

Starting a sprint

Click the 'Start sprint' button at the top of the Backlog. You should add a start and end date in the dialog box.
Click the 'Active sprints' link to the left of the project screen. This will show you what's called the 'boards'. As you work through the sprint, you will drag issues from the TO DO, to the IN PROGRESS, to the DONE boards.

Thursday, 14 March 2019

SCRUM, briefly

Product backlog

Product backlog (document) is created by product owner, It's a prioritised list of stuff which needs to be done from a business standpoint to realise the vision. It may have list items added or taken away.
People, users, stakeholders outside the project often want to know what's going on. The product backlog is their only interface to the project. They don't have access to the internal Scrum activity.

Sprint planning

The product owner and Scrum master sit down and look at the product backlog to agree the small collection of priority items which, when complete resemble a visible & quantifiable element of the project. This subset should take no more than 4 weeks (better less). When complete is added to an empty sprint backlog.

Separation of backlogs

Once the sprint backlog is full it will not be touched until the sprint is completed. No items which come into the product backlog will update the sprint backlog. If something needs adding the people requesting will only have to wait until the end of the sprint.

Sprint begins

Each day a called a stand-up meeting takes place with the scrum master and the people doing the work.
In stand-up meetings the workers say:

  • Here is what I did yesterday
  • Here is what I'm going to do today
  • Here is what is in my way

Sprint ends

There should be a potentially shippable product. The sprint backlog may now be cleared and not be revisited.
The sprint review takes place, which is a show and tell of the potentially shippable product created during the sprint.
The sprint review informs external users that progress has been made.

Product retrospective

After the sprint is over a product retrospective meeting takes place which includes the workers and and the Scrum master. It contains:

  • Lessons learned with a purpose
  • How they will continue to work

The Product retrospective feeds back to the process of taking the product backlog and adding entries to the sprint backlog.

Wednesday, 13 March 2019

Interacting with a vagrant box

SSH

The most common way of interacting with a vagrant box is through ssh. Once the box is up you can connect to it from your local terminal. Remember to be in the directory of you virtual box before doing anything. In my case it's ~/vagrant/centos65i686. Just type:
vagrant ssh

Synced Folders

The folder you used to launch your vagrant session, the one which contains Vagrantfile, can be accessed from you box after you have begun your ssh session as /vagrant. E.g.
vagrant ssh
ls /vagrant
would return Vagrantfile
During the next section titled 'Provisioning' we'll add a line to the Vagrant file to sync folders which enable the process of developing web content.

Provisioning

Vagrant can automatically install software when you vagrant up so that the guest machine can be repeatably created and ready-to-use. E.g.
Create bootstrap.sh in the same directory as your Vagrantfile with these contents.
#!/usr/bin/env bash
apt-get update
apt-get install -y apache2
Next, add these line to your Vagrantfile:
config.vm.synced_folder '.', "/var/www"
config.vm.provision :shell, path: "bootstrap.sh"
Once this is done, you'll need to reload the vagrant session and make sure that the provisioning is used thus:
vagrant reload --provision
If you're starting a session from scratch:
vagrant up --provision
will do.

Port Forwarding

During the provisioning stage we installed an Apache server. We also set up a synced folder so that whatever we had in our /vagrant folder could be served.
Port forwarding allows you to access a port on your own machine, but actually have all the network traffic forwarded to a specific port on the guest machine.
To achieve this add the following line to your Vagrantfile:
config.vm.network :forwarded_port, guest: 80, host: 4567
Then reload your session:
vagrant reload --provision
Now you should be able to access your box directory through your browser using the following URL
http://localhost:4567

When you want to finish your ssh session, just type
logout
If I mess up
If you make a bunch of changes which mess things up, don't worry. You can return the box to its original state by typing
vagrant destroy

Thursday, 7 March 2019

Using the Vanilla JS Component template with LAMP

I use the Vanilla JS Component at https://github.com/guitarbeerchocolate/vanilla-js-component, and you have LAMP server on my box. However, when I want to call PHP scripts which are on the LAMP server such as, in a POST request using fetch or XHR within JavaScript I get the following errors in my browser:
Access to XMLHttpRequest at 'http://localhost/test/vanilla-js-POST-JSON/login.php' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

postjson_xhr.js:19 Cross-Origin Read Blocking (CORB) blocked cross-origin response http://localhost/test/vanilla-js-POST-JSON/login.php with MIME type text/html. See https://www.chromestatus.com/feature/5629709824032768 for more details.

Obviously, it's treating the LAMP server like another domain.

The way to fix this is to put a line at the top of your PHP script thus:
header('Access-Control-Allow-Origin: *');
Happy coding.

Monday, 4 March 2019

Vagrant Virtual boxes (machines) on my old laptop

So, I've been playing around with Vagrant. It's been good, but I had a little pain early on because I have an old laptop. If you're a GNU/Linux user like me, you can get away with having an old laptop. I do most Vagrant things on the command-line, so the instructions below assume you're on GNU/Linux command and using the CLI.

How to install Vagrant

sudo apt update && sudo apt upgrade
sudo apt install virtualbox
sudo apt install vagrant -y

How to test the install has worked

vagrant --version

Create a sub-directory

I create a directory into which I will put all my boxes (virtual machines)
mkdir ~/vagrant
cd ~/vagrant

i686 example

Installing the box

As mentioned, I have an old laptop and therefore I can only run i686 boxes on it. You can find lots of boxes at https://app.vagrantup.com/boxes/search It was here that I searched for the term 'i686' and came up with the box 'herroffizier/centos-6.5-i686' which will be used in the example below. Still in the '~/vagrant' directory, create another sub-directory and change to it.
mkdir centos65i686
cd centos65i686
Now let's install the box.
vagrant init herroffizier/centos-6.5-i686
The installation takes place and a file called Vagrantfile is created. I like to make a few changes to this file for my own purposes. Here is my example Vagrant file below.
Vagrant.configure("2") do |config|
  config.vm.boot_timeout = 600
  config.vm.box = "herroffizier/centos-6.5-i686"
  config.vm.provider "virtualbox" do |vb|
    vb.gui = true
    vb.memory = "1024"
  end
end
I extended the timeout because I have an old laptop. I also load the GUI and give it a decent amount of memory.
Running the box
Now I'm ready to run my box. Still in the 'centos65i686' directory type the following.
vagrant up
A new window starts up and the box loads within it.
Once the loading process has completed you are presented with a login screen. Use the following credentials:
username : vagrant
password : vagrant
Now you should be in.

Tidying up

If you've finished with your box, you can close it down with the following command.
vagrant halt

Tuesday, 26 February 2019

Vanilla JavaScript Login form POST handler using XHR

I did a similar post to this called Vanilla JavaScript Login form POST handler using fetch. Fetch returns a JavaScript Promise, which can be a bit of a pain so I've also done a version using XHR, see below:

var postJSON = function(url, method, data, callback) {
  var xhr = new XMLHttpRequest();
  xhr.open(method, url, true);
  xhr.responseType = 'json';
  xhr.onload = function() {
    var status = xhr.status;
    if (status === 200) {
      callback(null, xhr.response);
    } else {
      callback(status, xhr.response);
    }
  };
  xhr.send(data);
};

Here's how to call it:
const form = document.querySelector('form');
form.addEventListener('submit', function(ev) {
  ev.preventDefault();
  const url = this.getAttribute('action');
  const method = this.getAttribute('method');

  postJSON(url, method, new FormData(form), function(error, json) {
    if (error !== null) {
      console.log('parsing failed', error);
    } else {
      console.log('json.username', json.username);
      console.log('json.password', json.password);
    }
  });
});