Laravel 6 – Build Your First Laravel Application

Laravel 6 – Build Your First Laravel Application

Introduction

Laravel is a powerful MVC PHP framework. From official docs “Laravel is a web application framework with expressive, elegant syntax”. You must’ve heard about Laravel if you’ve ever worked with PHP. Laravel has experienced major growth since it’s initial release in 2011. Laravel was created by Taylor Otwell. It became the most starred PHP framework on GitHub in 2015.

My goal with this article is to create a guide for those who just want to learn Laravel and explore PHP. This article will not cover every small detail about Laravel but will be enough to get you started with Laravel 6.

Prerequisites

  • You should be familiar with HTML, CSS & most important Object-Oriented programming with PHP 7
  • A local PHP environment (Valet, Homestead, Vagrant, XAMP, LAMP, etc.)
  • A database (MySQL, SQLite etc.)
  • Composer
  • Node & NPM installed and updated

Note: For local environment I’ll be using LAMP (Linux Apache MySQL PHP) as there are no pre-configured environment like Homestead or Valet available for Linux. You can use Homestead for windows or Valet if you’re a Mac user.

I’ll explain how to create a new Laravel 6 application just as I would in real world environment. So let’s get started.

Planning

You must plan any project before coding it out. Planning a project before implementation is a major factor in its success. It doesn’t matter how you plan a project. You can plan it on Paper, whiteboard or some simple text file. You can also use Trello for planning out all the components you’re going to create in the project.

Today, we are going to create a Contact Book app. So let’s talk about goals of it.

  1. Display all contacts in a list.
  2. Create a form where people can add new contact.
  3. Validate the form.
  4. Insert the data into the database.

Get Started

Let’s create a brand-new Laravel project. I like to put all my projects in Development directory. Open your terminal and navigate to this directory.

mkdir Development
cd Development

Next, let’s install Laravel’s command line installer.

composer global require "laravel/installer"

Now, create a new Laravel project.

laravel new ContactBook

This will create a new directory at Development/ContactBook and install a stock Laravel app.

Navigate to newly created directory and run Laravel server by

cd ContactBook
php artisan serve

You’ll get this output, open your browser and navigate to given address.

Default Laravel Homepage

Hurray! You’ve successfully installed default Laravel application.

Laravel 6 Environment File

Let’s open this newly created project in Editor. You can use any editor or IDE of your choice. My personal favorite IDE for Laravel development is PhpStorm. Now open .env (Environment) file.

Laravel environment file

Here, you can set different environment variables. You can change the name of the app by editing ‘APP_NAME’. The main part here is ‘DB_*’ variables. You can set different database by specifying driver name. Here you can also set SMTP details.

Setting up Authentication

Laravel made it very easy to enable Login/Registration functionality. In this tutorial, it’s not mandatory to set up authentication, so you can skip this part if you want to.

Laravel’s laravel/ui package provides a quick way to scaffold all the routes and views you need for authentication using a few simple commands:

composer require laravel/ui --dev
php artisan ui bootstrap --auth
npm install && npm run dev

This command will install a layout view, registration and login views, as well as routes for all authentication end-points. A HomeController will also be generated to handle post-login requests to your application’s dashboard.

With the basics set up and working, it’s time to start doing some coding.

Building a Contact List

Building a whole finished project is quite overwhelming, so it’s better if we divide our project in small parts. So let’s start with displaying a list of contacts. It may sound a small task but it still requires a database, table, view and query.

So let’s create a migration. We can create a migration by using Laravel artisan command line tool.

php artisan make:migration create_contact_books_table --create=contact_books

This command will create a new migration file database/migrations/{{datetime}}_create_contact_books_table.php

The file contains two methods: up and down. We’re interested in the up method for now. Add following columns in up method.

Schema::create('contact_books', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('phone')->unique();
            $table->text('description');
            $table->timestamps();
        });

Save it and run the migration by using following command.

php artisan migrate

Now, we’re going to need a model and some dummy data to work with our database. Laravel provides database seeder to populate table with dummy data and a factory class to generate dummy data.

php artisan make:model --factory ContactBook

This command will create a new Contact model. The --factory flag will generate a new factory file. Our newly created factory file will reside in database/factories. Open the ContactFactory.php file and fill the following:

$$factory->define(ContactBook::class, function (Faker $faker) {
    return [
        'name' => $faker->name,
        'phone' => $faker->phoneNumber,
        'description' => $faker->paragraph,
    ];
});

Now, let’s create a database seeder for contacts.

php artisan make:seeder ContactBookTableSeeder

This command will create a new seeder for our contact book table. Open the seeder file by going to database/seeds/ContactBookTableSeeder.php. Now paste the following in it.

 public function run()
 {
     factory(App\ContactBook::class, 5)->create();
 }

To activate the following, navigate to database/seeds/DatabaseSeeder.php. Now paste the following in it.

public function run()
{
     $this->call(ContactBookTableSeeder::class);
}

Now, run the migration and seed the tables by running the following command.

php artisan migrate:fresh --seed

We have successfully generated fake data for our app! Now we’re ready to create a new view to display a list of Contacts.

Routes & Views

Now it’s time to provide new routes to display a form to add new contact and list existing contacts. We can add new routes to our application in the routes/web.php file.

Here, we can create necessary routes for our app. Laravel provides a default route. To create a new route, we can either use dedicated controller class or closure. For sake of simplicity we’re going to use closure in our app.

Now, let’s update the home route to show all contacts from database table.

Route::get('/', function () {
    $contacts = App\ContactBook::all();

    return view('welcome', ['contacts' => $contacts]);
});

Here, in second argument we’re passing an array of contacts to our view welcome.

Next, edit the welcome.blade.php view to display our list of contacts.

<div class="content">
    <div class="col-md-12 mt-5 mb-5">
        <div class="text-center mb-3">
             <h3>Contact Book</h3>
        </div>
        <table class="table table-striped table-bordered table-dark">
            <thead>
               <tr>
                 <th width="20%">Contact Name</th>
                 <th width="20%">Phone Number</th>
                 <th>Description</th>
               </tr>
            </thead>
            <tbody>
            @foreach ($contacts as $contact)
              <tr>
                 <td>{{ $contact->name }}</td>
                 <td>{{ $contact->phone }}</td>
                 <td>{{ $contact->description }}</td>
              </tr>
            @endforeach
            </tbody>
        </table>
   </div>
</div>

Refresh the page in your browser.

All Contacts, listed in a table

New Contact Form

Now, it’s time to add a new form so user can add their own contacts in our table. To do that, first create a new route in our web.php file.

Route::get('/add', function (){
   return view('add');
});

Next, create a new view add.blade.php in our views folder. Add the following code in it.

@extends('layouts.app')
@section('content')
    <div class="container">
        <div class="row">
            <div class="col-md-6 offset-3">
                <div class="card">
                    <div class="card-header">
                        <h3>Add Contact</h3>
                    </div>
                    <div class="card-body">
                        <form action="/insert" method="post">
                            @csrf
                            <div class="form-group{{ $errors->has('name') ? ' has-error' : ''}}">
                                <label for="name">Name</label>
                                <input type="text" class="form-control" id="name" name="name" 
                                  placeholder="Name" value="{{ old('name') }}">
                                @if($errors->has('name'))
                                    <span class="help-block">{{ $errors->first('name') }}</span>
                                @endif
                            </div>
                            <div class="form-group{{ $errors->has('phone') ? ' has-error':'' }}">
                                <label for="phone">Phone</label>
                                <input type="text" class="form-control" id="phone" name="phone" 
                                 placeholder="Phone" value="{{ old('phone') }}">
                                @if($errors->has('phone'))
                                    <span class="help-block">{{ $errors->first('phone') }}</span>
                                @endif
                            </div>
                            <div class="form-group{{ $errors->has('description') ?' has- 
                             error':''}}">
                                <label for="description">Description</label>
                                <textarea class="form-control" id="description" 
                                  name="description"
                                  placeholder="description">{{ old('description') }}</textarea>
                                @if($errors->has('description'))
                                <span class="help-block">{{ $errors->first('description') </span>
                                @endif
                            </div>
                            <button type="submit" class="btn btn-primary">Add</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
@endsection

This will create a new form with 3 fields, name, phone and description. The form action is ‘/insert’ which we will next. Laravel require to send a csrf token with any type of form submission, so we’ve also included @csrf. This will create a hidden field with a random csrf token.

Navigate to ‘/add’ in your browser, you’ll see something like this.

Handling form submission

Now, with the form is created we can start working on our insert route, to handle the form submission. Open routes file and add the following.

use Illuminate\Http\Request;

Route::post('/insert', function (Request $request) {
    $data = $request->validate([
        'name' => 'required|max:100',
        'phone' => 'required|max:30',
        'description' => 'required|max:255',
    ]);

    $contact = tap(new App\ContactBook($data))->save();

    return redirect('/');
});

This route is a little complicated than others so let’s walk through it.

First, we are injecting the Illuminate\Http\Request object, which holds the POST data and other data about the request.

Next, we use the request’s validate() method to validate the form data. The validated fields are returned to the $data variable, and we can use them to populate our model.

We require all three fields, and using the pipe character; we can define multiple rules. If validation fails, an exception is thrown, and the route returns the user with the original input data and validation errors.

Next, we use the tap() helper function to create a new ContactBook model instance and then save it. Using tap allows us to call save() and still return the model instance after the save.

Now allow our model to populate given data, we’ve to specify “fillable” properties. Open ContactBook model and add the following.

class ContactBook extends Model
{
    protected $fillable = [
        'name',
        'phone',
        'description'
    ];
}

Now, let’s test this in our browser. Navigate to /add and submit the form with proper data.

Filling data in form
Our New Contact added to the bottom of the contact list

Conclusion

Congratulations, you’ve created your first Laravel 6 app. This article was designed to get you started on building your app, and you can use this as a building block to gain the skills you need to develop your application.

I hope you liked this article. Subscribe to our mailing list for more articles by me. Have a great day!

Introduction to Ruby on Rails

Introduction to Ruby on Rails

Have you been wondering how to build a web application? Perhaps you have started to learn programming languages but realizing that you had so much to climb the mountain and end up giving up. Or maybe you have been developing websites but it has been hard for you to maintain, keep track or upgrade your web application. In this article, we will learn about ruby on rails and the reasons behind using it as your backend development framework. I will also show you how to setup Ruby on Rails development environment and create a simple todo list application in few minutes with Ruby on Rails.

Getting to know Ruby on Rails

So let us address Ruby for a while before we go deep into this topic. Ruby is a programming language that was developed by Yukihiro Matsumoto from Japan in 1995. The idea of Ruby programming language is to put human need above computer needs, that is why Ruby is an object-oriented yet easy-to-use scripting language.

Okay, now we have a bit of history about Ruby programming language so let us talk ruby gems. Wait don’t get confessed yet, I am not talking about “a pink to blood-red colored gemstone”. What I talking about it is “a package manager for the Ruby programming language that provides a standard format for distributing Ruby programs and libraries, a tool designed to easily manage the installation of gems, and a server for distributing them”  that is conveniently named RubyGems.

Alright, let’s take a breather…

Since we know that Ruby is a “human-friendly” programming language creating RubyGems was essential to making the language more powerful for a longer time.

Okay, know most probably you are wondering so what is it about Rails then? 

In simple words, Rails is one of RubyGems. Rails is just a package that enables Ruby to run a webserver. So what is so special about it you might ask.

Rails

To begin with, Rails gem is not “only a package” but it is an entire framework for web development. Rails framework is built with the developers are in mind to keep the process of development as easy as it should be. It also has an easy learning curve compared to other frameworks. 

Oh boy, we are going into a bit of detail here but don’t worry it will all make sense eventually. 

Let start with, “Rails is a model-view-controller (MVC)” framework. 

Wait hold your horses… “MVC” what is this a channel name, something like MTV? 

Well, that would be awesome, but I am sorry; it is not a channel name. 

“MVC is an architectural pattern that separates an application into three main logical components. Each of these components are built to handle specific development aspects for an application” -wiki 

Sound complicated? Not really. Here how Rails MVC works: 

  • Model: is Responsible for storing and retrieving data
  • View: is Responsible for the rendering of the model (User interface)
  • Controller: is Responsible for responding to user input and instructing the model to respond to the user input 

A simple animated illustration is shown on how Rails MVC work is shown below:

Ruby on Rails Model-View-Controller (MVC)

Reasons why

Why Rails? Well, I will give you the reasons and you can be the judge of “why not rails?”

1. The process of development is much faster 

Due to the object-oriented nature of Ruby and the enormous collection of open source code available within the Rails community, Rails development process is much faster compare to other programming languages.

2. Developers find it easy to move between different Rails projects

As developers working in many projects, keeping track of what different project code doing could be hard. But not in rails because of each project your create uses the same structure and coding practices.

3. Rails is good for rapid application development (RAD)

Because it is easy to accommodate changes, Rails is a great framework for rapid application development; were RAD is a methodology that prioritizes fast prototype releases and repetitions.

4. Ruby code is “humanize code” and mostly self-documenting

Because Rails is build using Ruby, it takes advantage of ruby’s readability. which makes rails easy to pick up by other developers with code that has less documentation.

5. Develops a strong focus on testing

Rails have a strong testing framework that can test your application before deployment and helps developers find bugs or security threads.

6. Open source code

There are no licensing costs associated. Since Rails libraries are mostly open-source it is free to use for commercial uses, unlike other frameworks that have paid licensing.

Common concerns about ruby on rails

1. Hosts support for Rails

The support of hosting companies for Ruby on rails is not common. Comparing to PHP, javascript, Java, and C to Ruby, Ruby is a slow programming language. But it should not be a deal-breaker. With hosting providers like Heroku and EngineYard, you can deploy your application for the world to see in minutes.

2. Performance and Scalability

Rails applications are not as fast as Java or C, which is true. it does not stop big companies to rely on Rails as their primary framework. Big companies such as Airbnb, Twitch, Kickstarter and many more. The majority of applications developed by Rails are fast enough. Although Ruby on Rails is not the fastest programming language.


Ruby on Rails Development Environment setup

Setup on Mac/Linux machines

Installing homebrew (MAC/Linux)

Start by installing homebrew in your mac machine. To do so you have to run the following command in your terminal:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

Installing Ruby (MAC/Linux)

Now that we have Homebrew installed, we can use it to install Ruby.

We’re going to use rbenv to install and manage our Ruby versions.

To do this, run the following commands in your Terminal:

brew install rbenv ruby-build

# Add rbenv to bash so that it loads every time you open a terminal
echo 'if which rbenv > /dev/null; then eval "$(rbenv init -)"; fi' >> ~/.zshrc
source ~/.zshrc

# Install Ruby
rbenv install 2.7.0
rbenv global 2.7.0
ruby -v

Installing Rails (MAC/Linux)

Installing Rails is as simple as running the following command in your terminal:

gem install rails -v 6.0.2.1

Rails is now installed, but in order for us to use the rails executable, we need to tell rbenv to see it:

rbenv rehash

And now we can verify Rails is installed:

rails -v
# Rails 6.0.2.1

Setting Up A Database for macOS Searia

Rails ships with sqlite3 as the default database. Chances are you won’t want to use it because it’s stored as a simple file on disk. You’ll probably want something more robust like MySQL or PostgreSQL; but for our purposes, we will only need a simple setup to get started.

Because we can’t use the built-in sqlite3 version with macOS Sierra without running into some troubles, we’re going to install from homebrew.

brew install sqlite3

Setup on Windows machines

Installing Ruby (Windows)

To install Ruby for windows, you can go download the ruby installer and install it like any other application

Once you installed ruby go ahead and open the command prompt. to confirm ruby successfully installation you can type the following command

ruby -v 

Installing Rails (Window)

After installing ruby you can open the command prompt and type the following to install Rails

gem install rails

once you installed Rails, you can verify by typing the following:

rails -v 

and that should be it for windows users, lucky you windows user!

Creating your first Rails Application

Generate Rails Application Files

After installing Ruby on Rails we can start with creating a simple application to see how fast and easy it is to make solid applications using Rails. open your terminal/command line then navigate to where you want to create your project using cd command for example cd Desktop/

to create a new rails project you can type the following command:

rails new <name_of_your_project>

For our example, we are going to make a simple todo list application so if you want to follow along with type the following code instead:

rails new todolistapp

Creating a Database for Your Rails Appliaction

Then press enter and wait for the magic to happen. once rails finish generating your todo application you have to navigate to the newly created project folder:

cd todolistapp

then run the following code to create the database for your application

rake db:create

Starting Rails Server

once created the database try to run the rails server by typing

rails s

or

rails server

After run the rails server you can open a new browser window and load http://localhost:3000/ to view your newly created rails application.

Using rails scaffold to create a simple todo list application

Okay, you have come through so far. now we have a todo list app created and our server is loading the rails default page.

will now let us make it our own and change it to our needs.

let us list down the “todo list” for our todo list app: (sound funny when you put it this way) anyhow here:

  • database table for the todo list app.
  • model to update the database.
  • views to display the model data.
  • a controller that takes the user input and sends back view.

doesn’t that sound a lot todo? Well, it is a lot to do for creating a simple app like this! But not with Rails.

you can use two commands to do all of this for you.

Generate Scaffold

if you were following along and you still have the rails server open, you can press control-c into the terminal/command line to exit from the rails server first.

In the terminal, you can use this first command to create a scaffold:

rails g scaffold List title:string done:boolean

or

rails generate scaffold List title:string done:boolean

Database Migration

Then run the following code to create the database table for the list

rake db:migrate

and yes that is it you have created your first todo list application using rails.

Start Rails Server

run the server again using :

rails s

then go to http://localhost:3000/lists and test it yourself.

Changing the default route

now when you go to http://localhost:3000/ you still have the default rails page to get rid of it you should define a route to your application.

to do so you can open your project using Atom text editor if you have it installed by typing the following in your terminal

atom .

or just open the project folder with any text editor you currently have.

then navigate to config > routes as shown in the screenshot below:

once you open the file you can add the following :

root "lists#index"

your routes file code should look something list this:

Rails.application.routes.draw do
  resources :lists
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
  root "lists#index"
end

Adding bootstrap styling to your rails application

If you are following along, you have created an ugly todo list application, isn’t that an ugly-looking application. well, you can add a quick styling with bootstrap rails gem.

let’s rollback and start over. wait, start over ? yeah I said it. Rails can rollback without any issues but you have to do it in the current order.

Rails database rollback

First, let’s start with the database, we need to delete the table we have created. use the following command:

rake db:rollback

Congrats, the todo list table has been deleted.

Destroy Rails Scaffold

Next, delete the files that our scaffold created:

rails d scaffold List

or

rails destory scaffold List 

done, we are back to zero.

Installing Rails Gems

okay, let add our styling so our simple todo list app looks sexy.

First, we need to add Rails gems if you still remember what is gems rails gems do. okay, we already talk about gems in getting to know Ruby on Rails.

To add rails gems we have to open the gems file, you will find it the root directory of your application. “Gemfile”

you can add the following gems to the end of the file

gem 'jquery-rails'
gem 'bootstrap-generators', '~> 3.3.4'
gem 'record_tag_helper', '~> 1.0'

save the file and go back to the terminal/command line and type the following command to install the gems for your rails application

bundle i 

or

bundle install

Adding Bootstrap templates

After the gems bundle is installed, you need to replace the default scaffold view template to the bootstrap view templates. todo so you can run the following command:

rails generate bootstrap:install

the terminal might ask you if you want to replace some files, you can just type yes then press enter. once you done running the command you are ready to create a sexy looking todo list application.

Generating Rails scaffold

well, we have done this already,

In the terminal, you can use this first command to create a scaffold:

rails g scaffold List title:string done:boolean

or

rails generate scaffold List title:string done:boolean

Database Migration

then run the following code to create the database table for the list

rake db:migrate

and yes that is it you have created your sexy todo list application using rails.

Start Rails server

run the server and look at that

rails s

or

rails server

what a great looking todo list app, in few mins without writing a single line of code.

Great, it is a Wrap!

That is great, you have reached the end of this article. well done. so we have covered the following topic

  • A quick history about ruby on rails
  • Pointing out the good and bad about ruby on rails
  • Preparing Rails development environment
  • Created our first Rails app.
  • Rails rollback process
  • And the process of Rails gems installation

At the end of the day, Rails is a strong framework and learning it will ensure greater success in your career.

You can find the code for this article in GitHub

Serve Keras Model with Flask REST API

Serve Keras Model with Flask REST API

This tutorial will briefly discuss the benefits of serving a trained Machine Learning Model with an API. Then we will take a look at a precise example using a Keras Model and Python Flask to serve the model. You’ll learn how to Serve Keras Model with Flask REST API.

Why serve ML Model with API?

Flexibility

Encapsulation the execution and manipulation of your machine learning model with an API has a few benefits. Of the benefit is the abstraction layer that you create with an (REST) API. This abstraction layer enables you to

  • test your application more easily (with tools that can send API Requests but cannot import your Tensorflow/PyTorch model directly
  • develop your application (you can initiate an execution with a REST Plugin, with your Browser or in CLI with curl
  • share functionality as a service (by deploying and making accessible via HTTPS; deploying it as a micro-service)

Mobility

Since your Model now be tweaked with pure HTTP Requests, you can deploy your Model and access/manage it via Requests. No need to login into the SSH to change a cronjob, to change a limit of SQL Query or initiate a new build to deploy a newer version.

Also, with REST API you can deploy your model easily to services like AWS ElasticBeanstalk, Google AppEngine, etc. They all need a working Server in order to deploy your app. And now you can call your Model an Application, because in fact, it is.

Serving Keras Model with Flask

The following Application Structure and Code are just one of the many possibilities how tackle this idea. If you don’t like it, you can check out the CookieCutter Template for more structure and MetaFlow for a whole complete framework.

Folder Structure

We need following folders to encapsulate the scripts, classes etc.

In the screenshot below you can see that we have a folder with different models (model_x.py). We need this separation because you could have multiple Machine Learning Models that need to be served by the same Flask Server. Optionally you can create a ML Model Loader Class that will create Machine Learning Model based a configuration file (e.g saved in yaml, json or database).

Minimal Folder Structure for a ML Model serving Application in Python.

In the queries folder you store your (in most cases very long) SQL Queries. You replace certain options with {parameter_x}, e.g: LIMIT {limit}. This way you’ll be able to dynamically generate parameterized SQL Queries reading the .sql File:

sql_file.read().format(limit=10000)

Tests/ are for tests. We are going to skip this due to scope.

Config.py is for Configurations (SQL Creds, Server Envs, etc.). We are going to skip this due to scope.

Server.py is for Flask serving our Services.

Our Services do certain actions with our model. For example: “train_service” would initiate a training process for a certain model. “prediction_service” would initiate a prediction process for a model and so on.

Machine Learning Model Class

In the code section below you can see a simple DynamicModel class with only one method which return the the compiled Keras Model. This Model does not have to be static and can be outsourced into a “build_model()” method or similar. Also, all the parameters in the layers like the input_shape should be set via the method parameters from model(). Since this is only an introductory tutorial, many useful methods are missing in this class.

from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras import backend as K
import keras

"""
Author: Andrey Bulezyuk @ German IT Academy (git-academy.com)
Date: 18.01.2020
"""

class DynamicModel():
    def __init__(self, model_name = None):
        self.model_name = model_name 

    def model(self):
        model = Sequential()
        model.add(Conv2D(32, (5, 5), input_shape=(28, 28, 1), activation='relu'))
        model.add(MaxPooling2D())
        model.add(Dropout(0.2))
        model.add(Flatten())
        model.add(Dense(128, activation='relu'))
        model.add(Dense(10, activation='softmax'))

        model.compile(loss=keras.losses.categorical_crossentropy,
                    optimizer=keras.optimizers.Adadelta(),
                    metrics=['accuracy'])
        return model
        

Service Layer

Why do we need a service layer between Flask API (server.py) and the Machine Learning Model (dynamic_model.py)? Simple. By having this extra layer (service.py) you can execute the services (in our case Class Methods) not only via REST API, but also from within other python modules.

Our service layer is responsible for importing the DynamicModel Class, loading and saving the trained model for prediction or training respectively.

import sys, os, datetime
sys.path.insert(1, os.path.join(os.getcwd(), "src/models"))
from dynamic_model import DynamicModel
from keras.datasets import mnist
from keras.utils import np_utils
from keras.models import load_model

"""
Author: Andrey Bulezyuk @ German IT Academy (https://git-academy.com)
Date: 18.01.2020
"""

class Service():

    # model_name must be supplied. 
    # otherwise no configuration cad be loaded.
    def __init__(self, model_name=None):
        self.model_name = model_name
        self.dynamic_model = DynamicModel(self.model_name)

    def _get_train_data(self):
        (x_train, y_train), (x_test, y_test) = mnist.load_data()
        # reshape to be [samples][width][height][channels]
        x_train = x_train.reshape((x_train.shape[0], 28, 28, 1)).astype('float32')
        x_test = x_test.reshape((x_test.shape[0], 28, 28, 1)).astype('float32')
        
        y_train = np_utils.to_categorical(y_train)
        y_test = np_utils.to_categorical(y_test)

        self.x_train = x_train
        self.x_test = x_test

        self.y_train = y_train
        self.y_test = y_test

    def train(self):
        # Load data
        self._get_train_data()

        # This return the compiled Keras Model from dynamic_model->model()
        print(self.y_train)
        model = self.dynamic_model.model()
        model.fit(self.x_train, self.y_train,
            batch_size=1000,
            epochs=4,
            verbose=1) 

        # Save trained model
        now = datetime.datetime.now()
        model.save(f"src/models/{self.model_name}_{now.year}{now.month}{now.day}_{now.hour}{now.minute}.h5")
        return True


    def predict(self, X):
        # Load model
        model = self._load_model()
        
        # Execute
        results = model.predict(X)
        if results is not None and results != False:
            return results
        return False

The train method works perfectly fine. You can see this in the section below when we execute it via Flask REST API with curl. The predict service method is not functional yet. The code and explanation for this is outside of the scope of this tutorial. Keep checking our IT Course Shop for similar courses with more in-depth material.

Flask API Server

Our server part is pretty simple. We import flask and our Service class. We create a route called ‘service’ with two parameters: service_name (which can be train, predict, stop, status, history, …) and model_name. Based on the parameters we execute the specified service.

import sys, os, json
sys.path.insert(1, os.getcwd())
sys.path.insert(1, os.path.join(os.getcwd(), "src"))
from flask import Flask, request
from service import Service

"""
Author: Andrey Bulezyuk @ German IT Academy (https://git-academy.com)
Date: 18.01.2020
"""

application = Flask(__name__)

@application.route("/")
def hello():
    return "Hello World!"


@application.route("/<string:service_name>/<string:model_name>", methods=["GET", "POST"])
def service(service_name=None, model_name=None):
    service = Service(model_name=model_name)

    # GET Request is enough to trigger a training process
    if service_name == 'train':
        service.train()
    # POST Request is required to get the X data for prediction process
    elif service_name == 'predict':
        service.predict()

    return f"Service: {service_name}. Model: {model_name}. Success."

if __name__ == "__main__":
    application.run(debug=True)

Example CLI & GET REquest

C:\Users\andre\code\servekeraswithapi>curl localhost:5000/train/ModelA
Service: train. Model: ModelA. Success.
Epoch 1/4
60000/60000 [==============================] - 8s 141us/step - loss: 6.5852 - accuracy: 0.7280
Epoch 2/4
60000/60000 [==============================] - 8s 140us/step - loss: 0.3276 - accuracy: 0.9141
Epoch 3/4
60000/60000 [==============================] - 8s 140us/step - loss: 0.1897 - accuracy: 0.9495
Epoch 4/4
60000/60000 [==============================] - 8s 140us/step - loss: 0.1256 - accuracy: 0.9645
127.0.0.1 - - [18/Jan/2020 20:54:53] "GET /train/ModelA HTTP/1.1" 200 -

That’s it with our short tutorial. If you liked it, subscribe to our Newsletter for more Tutorials. If you have any Questions feel free to contact us or leave a comment.

Getting started with PHP 7 in 2020

Getting started with PHP 7 in 2020

What is PHP?

PHP stands for Hypertext Preprocessor (earlier called “Personal home page”). It is an open source scripting language created for the web development. PHP is a server-side language which means all the code is rendered on server and only static HTML, CSS and JavaScript is sent to the client’s browser. PHP is a back-end language which means no one on client side can check the code written in PHP, only the person with authority to access the server can check the source code. Now let’s explore reasons to learn PHP 7 in 2020 and what lies ahead for this simple and beautiful language.

Why should I learn PHP 7 in 2020?

PHP is compatible with all leading operating systems such as Windows, Linux, MAC OS and many others. Likewise, it is compatible with all popular web servers such as Apache, NGINXm IIS etc. PHP7 offers great compatibility and performance. Not only is it open source but also it contains many features and it is absolutely easy to install and set-up. We will cover installation part later in this article.

What are features of PHP?

PHP comes with many benefits that let you create wonderful web applications.

1. Open Source

PHP is an open source programming language which means it is free to use. There is a great community to help you if you get stuck anywhere and not able to figure out the problem.

2. Cross-Platform

PHP supports all major operating systems and servers.

3. Easy to use

PHP is simple and clean scripting language. Its syntax is convenient to use. Anyone can quickly learn PHP.

4. Performance

It is one of the fastest programming language. It takes so little time to establish a connection with database or fetch data from web services.

How to install PHP7?

You can follow this guide to install PHP7 in your preferred operating system.

Windows :

Step 1 – Download PHP7

Go to the official PHP website and download the latest version. Save it on your windows PC.

Figure 1

Step 2 – Extract the zip

Figure 2

Step 3 – Setting up Environment variable

We need to configure the environment variable to access PHP from the command line. You can follow these steps to do so.

Right click -> My Computer (This PC) -> Properties -> Advanced system settings

This will open a the following window.

Figure 3

Now click on Environment variables, select path under the System variables section and edit. Add the path of installed PHP to system path.

Click on the new button and add the path to the PHP bin. Save all changes and close all the windows. Now to verify the settings, open console (or CMD) and execute following.

FIgure 4

If you get the following output, it means PHP is successfully installed on Windows.

Linux:

Here, we will see the steps to install PHP in Ubuntu Linux.

Step 1 – Update Ubuntu

Before installing anything new, you should always update your system. Open a terminal and run the following commands:

apt-get upgrade && apt-get update

Step 2 – Install PHP7

You can install PHP7 from Ubuntu’s official repository by following command:

apt-get install php

This command will install PHP7 and it’s required dependencies. To check whether PHP is installed or not execute following command:

php -v

It will return the PHP version related information.

PHP7 Syntax Overview

Like any other programming language PHP has a set of syntax rules which we need to follow while programming. PHP files commonly have a .php file extension as they’re always executed on server.

Tags in PHP or Escaping to PHP

The PHP parsing engine needs a way to differentiate PHP code from other elements. PHP tags are used for this.

We can ‘Escape to PHP’ by using the following 4 methods:

  1. Canonical PHP tags
  2. SGML (or) Short HTML Tags
  3. HTML Script Tags
  4. ASP Style Tags

From all of the above, Canonical PHP tags are most commonly used and are compatible with majority of servers.

Example:

<?php
    # Here the echo command prints the message
    echo "Hello world";
?>
Comments in PHP

Comments are statements in a program by developers which describe the intent and purpose of the code. There are 2 styles for comments in PHP. Comments in PHP code are not read or executed by the PHP engine. Therefore, they do not affect the output.

Single Line Comment

<?php
// This is a single line comment

echo "Hello World";

# This is also a single line comment
?>

Multi line Comment

<?php
/* 
Example for multiline comment
This is a multiline comment
*/

echo "Hello world";
?>
PHP Syntax is Case-Sensitive

In PHP besides variables, all other keywords are not case-sensitives. We have to be very careful while defining and using variables. Look at this example.

<?php
// Here all echo statements will execute
// in the same manner because keywords are case-insensitive

$variable = "Test";
ECHO $variable;

// You will get an "Undefined Variable" error
// Because variable names are case-sensitives

echo $VARIABLE;
?>

If you want to build a fast and beautiful Frontend for you PHP-Backend Application, consider the popular Framework Vue.JS 2 Course.

PHP Data types & Variables

Data Types

A Data type is the classification of data into a category according to its attributes. There are 4 major data types in PHP.

  • Integer – eg. 1, 1000, -12
  • Float – eg. 3.14
  • String – eg. “Test String”
  • Boolean – eg. True or False
Variables

A variable is a name given to a memory location that stores data at runtime. There are 2 types of variables, Global variables and Local variables. There are some pre-defined rules to create variables.

  • All variable names must start with the dollar sign. – eg. $testVariable
  • Variable names are case sensitive.
  • All variable names must start with a character.
  • Variable names must not contain any whitespaces between them.

PHP Control Structure – If else

If else is the simplest control structure. And it is relatively easy to understand even in PHP 7 in 2020. It evaluates the conditions using Boolean logic. Take a look at the following code snippet:

<?php
if (condition is true) {
   // Code block one
}else {
   // Code block two
}
?>

Here,

  • “(condition is true)” is the control structure, if it evaluates to true, “Code Block one” will be executed
  • If condition evaluates to false, “Code block two” will be executed.
  • In any situation only one of the following blocks will be executed.
<?php

// If else example

$x = 10;
$y = 20;

if($x > $y) {
    
    echo "$x is greater than $y";

} else {

    echo "$y is greater than $x";

}

// Output: 20 is greater than 10

?>

PHP Loops

While Loop

The while loop is use to execute a block of code repeatedly until the codition gets statisfied.

<?php

while (condition) {
    // Code to execute
}

?>

Here,

  • Code inside of while loop will be executes until the given “condition” is true.
<?php

$i = 0;

while ($i < 5) {
    echo $i;
    $i++;
}

/*
Output:

0
1
2
3
4

*/

?>
For Loop

For loop executes the block of code a specified number of times.

<?php

To (initialization; condition; increment/decrement) {

    // Code to be executed

}

?>

Here,

  • “initialize” is used to set the counter’s initial value.
  • “condition” is the condition that is evaluated for each loop iteration.
  • “increment/decrement” is used to increment or decrement the counter.
<?php

for ($i = 0; $i < 5; $i++) {
    echo $i;
}

/*
Output:
0
1
2
3
4
*/

?>
ForEach Loop

The php foreach loop is used to iterate through array values.

<?php

foreach($array_variable  as $array_value){

    //Code block to be executed

}

?>

Here,

  • $array_variable is the array variable to be looped through.
  • $array_value is the temporary variable that holds the current array item.
<?php

$arr = [1, 2, 3, 4, 5]

foreach ($arr as $item) {
    echo $item;
}

/*
Output:
1
2
3
4
5
*/

?>

Executing PHP File

There are two ways to execute PHP files.

  1. Executing PHP file in browser
  2. Executing PHP file in terminal (command line)
Executing PHP file in browser

Step 1: Create your PHP file in www or htdocs folder of your server.

Step 2: Turn on your server.

Step 3: Go to http://localhost/<file_name>

Figure 5
Executing PHP file from terminal (command line)

Step 1: Open your preferred terminal

Step 2: Navigate to your file location (directory)

Step 3: Execute the file by following command

php <filename.php>
Figure 6

As you can see, it will one of the best skills you could acquire for yourself and your resume. We are certain that PHP 7 in 2020, will have a continuously growing community.

How to Run Moodle with Docker Compose

How to Run Moodle with Docker Compose

In this tutorial we are going to have a Moodle Instance up and running on a Virtual Machine – inside Docker Containers.

First of all, install and get Docker up and running. Then, download Moodle or make sure you have a Git-Repository ready at hand. We are going to use docker-compose for this task. Now let’s try and Run Moodle with Docker.

Moodle with Docker

We need a container that will have all the needed technology to run and serve the Moodle source code (your repository). This configuration will come from an Image, that we will use and configure through a docker-compose.yml file. Create a file docker-compose.yml and insert the version of docker-compose syntax that we are going to use:

version: "3.3"

These Technologies are needed:

  • Moodle Container
    • Operating System (Ubuntu)
    • Server (Apache2, Nginx)
    • PHP7.x (incl. php-curl, php-mysql, etc.)
  • Database Container
    • MariaDB 10+

Database Docker Image

We are going to use a simple and straightforward solution from bitnami. We simple create a service that will use this image, and set some parameters like username, db_name, etc.

services:
  mariadb:
    image: "bitnami/mariadb:10.1"
    networks:
      - moodle-net
    environment:
      - MARIADB_USER=bn_moodle
      - MARIADB_DATABASE=bitnami_moodle
      - ALLOW_EMPTY_PASSWORD=yes
    volumes:
      - type: bind
        source: /home/maria_data
        target: /bitnami
    ports:
      - "3306:3306"

We call our service ‘mariadb’, expose some ports (3306) and bind a volume to persist our data on our host machine. We also attach ‘mariadb’ to a network moodle-net. Also, make sure that docker can read/write the /home/maria_data folder on your host. We set rwx access for now (which is not recommended), please make sure to set the proper rights.

sudo chmod a+rwx /home/maria_data/

Server Docker Image

There are already built images for these technologies: webdevops/php-apache:7.3 & bitnami/mariadb.

Let’s pull and test the PHP & Apache image first.

#Download
docker pull webdevops/php-apache:7.3

# Run Image (Copy image ID. 'docker images')
docker run -d -p 80:80 efec3d223189

Now navigate to localhost or your public IP Address. You should see an empty Apache2 page.

Moodle and Docker

This page is the result of the file ‘index.php’ in container in folder /app. Worked fine. To use this image as a service in our config file, we need to create a new service in docker-compose.yml.

  moodle:
    image: "webdevops/php-apache:7.3"
    networks:
      - moodle-net
    environment:
      - MOODLE_DBHOST=mariadb
      - MOODLE_DBPORT=3306
      - MOODLE_DBUSER=bn_moodle
      - MOODLE_DBPASS=''
      - MOODLE_DBNAME=bitnami_moodle
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - type: bind
        source: /home/moodle_data
        target: /moodledata/moodledata
      - type: bind
        source: /home/gita-moodle
        target: /app
    depends_on:
      - mariadb

We specify the image that we tested previously. Specify the network to be same as the network of mariadb container. The Env Vars that we define, will be used by moodle in config.php. We open ports and specify the volumes. We make sure that moodle container only starts after mariadb container is up with the depends_on option. Make sure /home/moodle_data is writable.

sudo chmod a+rwx /home/moodle_data/

Before we continue, in these courses you can learn how to create backend and frontend application. Both of which you can easily deploy and serve with Docker. And now you know how to use docker-compose. Expand your skill-set with these courses.

Finish line

At last, we need to define our network and volumes:

networks:
  moodle-net:
    driver: bridge

volumes:
  mariadb_data:
    driver: local
  moodle_data:
    driver: local

Now let’s boot up these containers with and visit localhost or your public ip.

docker-compose up -d

You should see the installation process. Enter your Database data (see ENV VARS in MariaDB Service. After that a config.php file will be created. If not, copy the code and create a config.php file in root folder.

Moodle Installation process Docker

After finishing up the setup process of moodle, you’ll finally see your ready working moodle instance. Now you run Moodle with Docker Containers.

After setting up moodle. Your host volumes/folders will be filled with data that comes from containers. E.g. moodle population a predefined folder structure in moodle_data.

ls moodle_data/
cache  filedir  lang  localcache  lock  moodle  muc  sessions  temp  trashdir

Same, and more importantly, applies to mariadb container. Our Database is now persisted on our host machine.

/home/maria_data/mariadb/data# pwd
/home/maria_data/mariadb/data
/home/maria_data/mariadb/data# ls
aria_log.00000001  aria_log_control  bitnami_moodle  ibdata1  ib_logfile0  ib_logfile1  multi-master.info  mysql  mysql_upgrade_info  performance_schema  tc.log  test

Andrey Bulezyuk

German IT Academy Coach

Andrey Bulezyuk is the founder of German IT Academy and a course creator. He mainly covers topics from Web Development (NodeJS, VueJS, Django etc.) to Data Science (Pandas, Numpy) and Machine Learning (Tensorflow, Keras, etc.). He published a German book “Algorithmic Trading“, giving his readers the opportunity to learn how to code automatic trading systems for the stock market or the Forex. He has experience as a Backend and Frontend Developer. In his early years he worked on Web Projects as a Freelancer. Switched later to Financial Market System Developing. Currently employed as Machine Learning Engineer. He takes part in different projects and acts as a Co-Founder in different small start-ups. Andrey Bulezyuk was an employed Full-Stack Developer in Munich. Currently his duties do cover areas of Machine Learning and ETL.