Category Archives: EnvatoTutsCode

Get Started With Vue Router

Introduction

Routing becomes an important feature to put in place when you have many components. Thanks to the awesome Vue.js team, this is easy using vue-router.

In this tutorial, you will see how to use vue-router while building a simple Vue.js application.

Set Up the Application

You will make use of Vue-CLI to set up your application for this tutorial. If you do not have it installed already on your machine, you can do so by running:

npm install -g vue-cli 

With that done, you can set up your application using the command below.

vue init webpack router-app

You are going to be asked some questions. One of these questions is: Install vue-router? For that, enter y.

Navigate to your project folder from your terminal:

cd router-app

Run the command to install all dependencies:

npm install

Start your development server by running:

npm run dev

If you want to install vue-router manually, you can use the command below.

npm install vue-router --save

Integrate Vue-Router

When using Vue-CLI, the router gets activated by default. You can see that in your src/router/index.js file.

#src/router/index.js

import Vue from 'vue' // 1
import Router from 'vue-router' // 2
import HelloWorld from '@/components/HelloWorld' // 3

Vue.use(Router) // 4

export default new Router({ // 5
  routes: [
    {
      path: '/',
      name: 'Hello',
      component: HelloWorld
    }
  ]
})
  1. Vue is imported from vue.
  2. Router is imported from the vue-router package.
  3. HelloWorld is imported from the components folder. We’ll talk more about this later.
  4. Router is mounted as middleware to your project.
  5. A default route configuration is created. The route is an array of a JavaScript object. It consists of a path, name, and component. The path gets appended to the URL of your web application. The route created above is meant for the home page. You can change the path to /hello, and it will no longer work for the home page. It will only be triggered when you visit the /hello path of your application. The component tells the route the component you want to load when that path is visited. This is the reason you imported the HelloWorld component. This route is exported as Router.

The exported Router has to be imported in your src/main.js file. This is important for the routes to work. This is taken care of when working with Vue-CLI. Your src/main.js should look like this:

#src/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' // 1 Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, // 2 template: '<App/>', components: { App } })
  1. The router is imported from your router folder.
  2. The imported router is used when creating a new Vue instance.

Standard Routes

The route you saw above is an example of a standard route. A standard route is one having a path, component, and name. Let’s create our own route. Try this part out yourself using the flow below.

  1. Create a new component called Pack. You need to have some dummy text.
  2. Go to your src/router/index.js, import the new component you created, and add a new path.
  3. Open your browser and point to the new path.

I bet you were able to do that on your own. Let’s try it out together.

Here is what my Pack component looks like.

#src/components/Pack.vue

<template>
  <div class="hello">
    <h1>Pack Component</h1>
    <p>This is a pack component. It is supposed to be a pack of wolves, but the wolves got trap in this tiny component</p>
  </div>
</template>

<script>
export default {
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

read more

Implementing an Event Bus With LiveData

Final product image
What You’ll Be Creating

At the last Google I/O, the Android team released a set of powerful Android Architecture Components. They call it:

A collection of libraries that help you design robust, testable, and maintainable apps. Start with classes for managing your UI component lifecycle and handling data persistence.

If you haven’t learnt about them, you are strongly advised to check out our awesome series here on Envato Tuts+ about Android Architecture Components by Tin Megali. Make sure you go dive in! 

In this tutorial, I’ll show you how to use the LiveData components from the Android Architectural Components to create an event bus. An event bus can be used to effectively communicate between Android components or between layers of your application—for example, communicating to an Activity from an IntentService that a file has finished downloading. 

We’ll build a very simple app that triggers an IntentService to do some work—from an Activity. Our IntentService will then communicate back to the Activity when the work is completed. Our communication channel will be from the LiveData library. 

Prerequisites

To be able to follow this tutorial, you’ll need:

You can also learn all the ins and outs of the Kotlin language in my Kotlin From Scratch series.

1. Create an Android Studio Project

Fire up Android Studio 3 and create a new project with an empty activity called MainActivity

Android Studio new project screen

2. Add the Lifecycle Components

After creating a new project, specify the LifeCycle and the LiveData artifacts in your app module’s build.gradle. Note that as of this writing, the new architectural components are now in a stable version. So this means you can start using them in production apps. 

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.1.0'
    
    implementation "android.arch.lifecycle:runtime:1.0.3"
    implementation "android.arch.lifecycle:extensions:1.0.0"
}

These artifacts are available at Google’s Maven repository. 

allprojects {
    repositories {
        google()
        jcenter()
    }
}

By adding the dependencies, we have taught gradle how to find the library. Make sure you remember to sync your project after adding them. 

3. Create the LifecycleOwner Activity Subclass

Here our MainActivity implements the LifecycleOwner interface. 

import android.arch.lifecycle.Lifecycle
import android.arch.lifecycle.LifecycleOwner
import android.arch.lifecycle.LifecycleRegistry
import android.arch.lifecycle.Observer
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.widget.Button
import android.widget.TextView

class MainActivity : AppCompatActivity(), LifecycleOwner {
    private val registry = LifecycleRegistry(this)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        registry.handleLifecycleEvent(Lifecycle.Event.ON_CREATE)
    }

    override fun getLifecycle() : Lifecycle = registry

    override fun onStart() {
        super.onStart()
        registry.handleLifecycleEvent(Lifecycle.Event.ON_START)
    }

    override fun onResume() {
        super.onResume()
        registry.handleLifecycleEvent(Lifecycle.Event.ON_RESUME)
    }

    override fun onPause() {
        super.onPause()
        registry.handleLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    }

    override fun onStop() {
        super.onStop()
        registry.handleLifecycleEvent(Lifecycle.Event.ON_STOP)
    }

    override fun onDestroy() {
        super.onDestroy()
        registry.handleLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    }
}

read more

Building a Slack Bot Using Python

Final product image
What You’ll Be Creating

Slack was founded in 2014 and is being touted as the fastest-growing business application in history. It currently has over 50,000 paying companies using its product—including my current place of employment.

Slack has really distinguished itself from its predecessors that were more focused on being a messaging system with some voice and video capabilities. Slack has really pushed the envelope and is working diligently on building on a very powerful App Directory. The App Directory contains hundreds to thousands of integrations that can provide an incredible amount of flexibility to improve your company’s efficiency.

The goal of this article is to demonstrate how you can build your own unique integration with Slack, leveraging Python for the logic.

To help focus on understanding the mechanics of a Slack Bot’s basics, I will focus on a custom bot.

Why Build a Slack Bot?

Even though Slack has a world-class App Directory, each business has unique business processes. This leaves many companies in a situation where they simply cannot find the perfect application for them.

This is where building your own Slack Bot comes into play.

A Slack Bot’s job is to receive and handle events generated by your team’s Slack interaction. Slack provides at least 50 different event types, such as:

  • message: A message was sent to a channel.
  • team_join: A new member has joined the team.
  • member_joined_channel: A user joined a public or private channel.

And of course, there are many more event types that your bot can optionally handle and react to. For example, the team_join event is a fantastic event that can begin an entire onboarding process.

The goal of this article will demonstrate how a Slack Bot will interact with the message event to perform specific actions when team members interact with the bot.

Picking the Right Slack Bot Type

In this article, I will create a Python application and a Slack Bot that can be added to your team project to respond to the message event.

To begin, I need to create a Bot on Slack. Two types of bots can be created:

  • a custom bot
  • creating an application and adding a bot user

This article will create a custom bot because an application bot user would be more appropriate if I were planning to write and publish an application on Slack. Given that I wish this bot to be private to my team, a custom bot will suffice.

Create a Custom Slack Bot

A custom bot can be created here: https://my.slack.com/apps/A0F7YS25R-bots. If you are already logged in to your Slack account, on the left select the Add Configuration button; otherwise, log in to your Slack account before proceeding. If you do not have a Slack account, you can sign up for free.

This will take you to a new page that requires you to provide a username for your bot. Enter your username now, ensuring you follow Slack’s naming guidelines. Once you have selected an awesome bot name, press Add bot configuration.

After you have successfully created your bot, Slack redirects you to a page that allows for further customization of your bot. I’ll leave that part to your creative self. The only thing needed from this page is the API Token that starts with xoxb-. I would either copy this token to a safe place for later use or simply leave this page open until we need the token for the Python application.

Setting Up Your Python Application

According to Slack’s official documentation for the Slack Developer Kit for Python, it currently supports version 2.7. It does make mention that version 3 will be supported in the near future.

I’ve already got version 2.7 installed, so I will stick with that version of Python for now. If your Python installation is already set up and ready to go, you can move on to the next step; otherwise, please visit the Python Download page and download the appropriate version for your operating system.

To install the Slack Developer Kit, I will use PyPi to simplify the installation of the Slack Client. On some operating systems, the pip command can be run directly from a command prompt. If not, you would need to reference the entire path to the pip program.

For example, on my Windows system, I ran the following command to install the Slack Client from a command prompt (referencing the full path to the pip.exe file): \Python27\Scripts\pip
install slackclient
.

Next, you will want to choose a location to house your application. I enjoy using GitHub, so I created a main python folder that contains all of my different Python applications. Inside this folder, I made a sub-folder appropriately called slackbot.

Once I’ve chosen where my application will be hosted, I’m going to store the core of my application in a file called slackbot.py.

Your First Slack API Call

It’s time to lay fingers to the keyboard and connect to Slack and make our first API call. Let’s get right to the code, and I’ll explain what’s happening after:

from slackclient import SlackClient

slack_client = SlackClient("xoxb-*******************")

api_call = slack_client.api_call("users.list")
if api_call.get('ok'):
	users = api_call.get('members')
	for user in users:
		print user.get('name')

The code begins with importing the Slack Client library, followed by instantiating the SlackClient class with your Slack Bot’s API Token that you saved earlier. Be sure to replace the example token in this example with your token.

The SlackClient object is stored in a local variable called slack_client that will be used to interact further with Slack.

Using the slack_client, an API call is made to retrieve a list of your team’s users. If the API call succeeded, the list of team members is stored in the users variable. The users variable is an array that, using a for loop, prints each team member’s name to the console application. 

Slack supports several different types of interactions with the system. The first, which we just completed, made an API call. Slack offers many other types of API calls: Web APIEvents APIConversations APIReal Time Messaging API, and SCIM API. The API call we made to retrieve the list of users leveraged the SCIM API.

In the next example, I will demonstrate how to use the Real Time Messaging System. Once we begin building the final bot, the Conversations API will be used to send messages in response to the commands our bot will respond to.

Connecting to the Real Time Messaging System

The RTM system provides a lot of power because Slack sends events that your application can handle and respond to immediately. Of course, there are so many events that your bot may not need to handle every event. To demonstrate the many different events that occur simply upon connection, the following example will output each event that is received.

Let’s immediately look at the code to connect and begin receiving Slack events:

from slackclient import SlackClient
import time

slack_client = SlackClient("xoxb-****************")

if slack_client.rtm_connect(with_team_state=False):
	print "Successfully connected, listening for events"
	while True:
		print slack_client.rtm_read()
		
		time.sleep(1)
else:
	print "Connection Failed"

read more

How to Create a Custom Authentication Guard in Laravel

In this article, we’re going to cover the authentication system in the Laravel framework. The main aim of this article is to create a custom authentication guard by extending the core authentication system.

Laravel provides a very solid authentication system in the core that makes the implementation of basic authentication a breeze. In fact, you just need to run a couple of artisan commands to set up the scaffolding of an authentication system.

Moreover, the system itself is designed in such a way that you could extend it and plug in your custom authentication adapters as well. That’s what we’ll discuss in detail throughout this article. Before we go ahead and dive into the implementation of the custom authentication guard, we’ll start with a discussion of the basic elements in the Laravel authentication system—guards and providers.

The Core Elements: Guards and Providers

The Laravel authentication system is made up of two elements at its core—guards and providers.

Guards

You could think of a guard as a way of supplying the logic that’s used to identify the authenticated users. In the core, Laravel provides different guards like session and token. The session guard maintains the state of the user in each request by cookies, and on the other hand the token guard authenticates the user by checking a valid token in every request.

So, as you can see, the guard defines the logic of authentication, and it’s not necessary that it always deals with that by retrieving valid credentials from the back end. You may implement a guard that simply checks the presence of a specific thing in request headers and authenticates users based on that.

Later in this article, we’ll implement a guard that checks certain JSON parameters in request headers and retrieves the valid user from the MongoDB back end.

Providers

If the guard defines the logic of authentication, the authentication provider is responsible for retrieving the user from the back-end storage. If the guard requires that the user must be validated against the back-end storage then the implementation of retrieving the user goes into the authentication provider.

Laravel ships with two default authentication providers—Database and Eloquent. The Database authentication provider deals with the straightforward retrieval of the user credentials from the back-end storage, while Eloquent provides an abstraction layer that does the needful.

In our example, we’ll implement a MongoDB authentication provider that fetches the user credentials from the MongoDB back end.

So that was a basic introduction to guards and providers in the Laravel authentication system. From the next section onwards, we’ll focus on the development of the custom authentication guard and provider!

A Quick Glance at the File Setup

Let’s have a quick look at the list of files that we’ll implement throughout the course of this article.

  • config/auth.php: It’s the authentication configuration file in which we’ll add an entry of our custom guard.
  • config/mongo.php: It’s the file that holds the MongoDB configuration.
  • app/Services/Contracts/NosqlServiceInterface.php: It’s an interface that our custom Mongo database class implements.
  • app/Database/MongoDatabase.php: It’s a main database class that interacts with MongoDB.
  • app/Models/Auth/User.php: It’s the User model class that implements the Authenticable contract.
  • app/Extensions/MongoUserProvider.php: It’s an implementation of the authentication provider.
  • app/Services/Auth/JsonGuard.php: It’s an implementation of the authentication guard driver.
  • app/Providers/AuthServiceProvider.php: This is an existing file that we’ll use to add our service container bindings.
  • app/Http/Controllers/MongoController.php: It’s a demo controller file that we’ll implement to test our custom guard.

Don’t worry if the list of the files doesn’t make much sense yet as we’ll discuss everything in detail as we go through it.

Deep Dive Into the Implementation

In this section, we’ll go through the implementation of the required files.

The first thing that we need to do is to inform Laravel about our custom guard. Go ahead and enter the custom guard details in the config/auth.php file as shown.

...
...
'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'users',
    ],
    
    'custom' => [
      'driver' => 'json',
      'provider' => 'mongo',
    ],
],
...
...

As you can see, we’ve added our custom guard under the custom key.

Next, we need to add an associated provider entry in the providers section.

...
...
'providers' => [
    'users' => [
        'driver' => 'eloquent',
        'model' => App\User::class,
    ],
    'mongo' => [
        'driver' => 'mongo'
    ],

    // 'users' => [
    //     'driver' => 'database',
    //     'table' => 'users',
    // ],
],
...
...

read more

New Course: Code a watchOS App With Swift

Final product image
What You’ll Be Creating

The Apple Watch is becoming more and more popular—if you don’t know how to create apps for it, you’re missing out on a useful opportunity.

Our new course, Code a watchOS App With Swift, shows you how to create a simple Apple Watch app with WatchKit, using some very basic skills and technologies. 

Follow along with Derek Jensen across all 19 videos and 2.3 hours of instructions, and you’ll learn how to create a watchOS project and how to design an app with the Interface Builder. Along the way, you’ll learn how to use some really useful UI components and even how to integrate haptic feedback in your app.

read more