MongoDB Fresh Install in Mac OS X

Today i need MongoDB for my project, and i forget that in my laptop don’t have MongoDB installed yet. lets get started to installing MongoDB in Mac OS X.

Download and extract
go to MongoDB Official website to download the package.
$tar xvz mongodb.xxx.xxxx.tgz
$sudo mv mongodb.xxx.xxxx /usr/local/mongodb

Add MongoDB data directory
$mkdir -p /data/db
$sudo chown user /data/db

Add MongoDB/bin $PATH
$vim ~/.bash_profile

export MONGO_PATH=/usr/local/mongodb
export PATH=$PATH:$MONGO_PATH/bin

$source ~/.bash_profile
$mongo -version
MongoDB shell version: x.x.x

Starting MongoDB
Terminal 1
$mongod
....
waiting for connections on port 27017

Terminal 2
$mongo
MongoDB shell version: x.x.x
connecting to: test
> show dbs
local 0.00GB

Create AutoStart MongoDB

$ sudo vi /Library/LaunchDaemons/mongodb.plist

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>mongodb</string>
  <key>ProgramArguments</key>
  <array>
    <string>/usr/local/mongodb/bin/mongod</string>
  </array>
  <key>RunAtLoad</key>
  <true/>
  <key>KeepAlive</key>
  <true/>
  <key>WorkingDirectory</key>
  <string>/usr/local/mongodb</string>
  <key>StandardErrorPath</key>
  <string>/var/log/mongodb/error.log</string>
  <key>StandardOutPath</key>
  <string>/var/log/mongodb/output.log</string>
</dict>
</plist>

$sudo launchctl load /Library/LaunchDaemons/mongodb.plist

try to start mongodb again by type:

$mongo

Simple RESTfull API with Lumen – Laravel Microframework

Lumen is Laravel micro-framework that build for small web application and handle some micro-services. Nowadays people love to use Lumen for build fast API for their application.

Installing Lumen

if you have installed lumen installer using composer, you just need to type:

lumen new api

note

api : directory of project that you want to start build

or you can install lumen via composer create-project:

composer create-project laravel/lumen --prefer-dist api

Check all your artisan command by type:

php artisan

Run lumen on your local server

php artisan serve

 

Screen Shot 2015-12-29 at 9.12.45 PM

For full documentation you can read here.

when the package downloaded, you can start modify .env file from rename .env.example file. Fill the database detail setting to connect with your database in your local machine.

APP_ENV=local
APP_DEBUG=true
APP_KEY=SomeRandomKey!!!
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
DB_CONNECTION=mysql
DB_HOST=DATABASE_HOST
DB_DATABASE=DATABASE_NAME
DB_USERNAME=DATABASE_USER_NAME
DB_PASSWORD=DATABASE_PASSWORD

In the api/bootstrap/app.php uncommenting this following line:


Dotenv::load(__DIR__.'/../');
$app->withFacades();
$app->withEloquent();

 

Migration
this step is to create table in your database. In this example, there are article table that consist of 6 column.
id (auto increment), title varchar, content text, author varchar, update_at timestamp, and created_at timestamp.


php artisan make:migration --create=article create_article_table

 

it will create migration file under /database/migration . Edit xxx_create_article_table.php file

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateArticleTable extends Migration {
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('article', function(Blueprint $table)
        {
            $table->increments('id');
            $table->string('title');
            $table->text('content');
            $table->string('author');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('article');
    }
}
save and run :

php artisan migrate

you are now success to create article table in your database.

 

Model
create article model under App/Article.php
<?php namespace App;
 
use Illuminate\Database\Eloquent\Model;
class Article extends Model
{
     protected $fillable = ['title', 'content', 'author'];
    
}
?>

 

Controller

create article controller under app/Http/Controllers/ArticleController.php

<?php
namespace App\Http\Controllers;
use App\Book;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class ArticleController extends Controller{
    public function index(){
        $Articles  = Article::all();
        return response()->json($Articles);
    }
 
    public function getArticle($id){
        $Article  = Article::find($id);
        return response()->json($Article);
    }
 
    public function createArticle(Request $request){
        $Article =Article::create($request->all());
        return response()->json($Article);
 
    }
 
    public function deleteArticle($id){
        $Article  =Article::find($id);
        $Article->delete();
        return response()->json('success');
    }
 
    public function updateArticle(Request $request,$id){
        $Article  =Article::find($id);
        $Article->title = $request->input('title');
        $Article->content = $request->input('content');
        $Article->author = $request->input('author');
        $Article->save();
        return response()->json($Article);
    }
 
}

Routing
Add your routing under app/Http/routes.php


$app->get('/', function () use ($app) {
return $app->welcome();
});
$app->group(['prefix' => 'api/v1','namespace' => 'App\Http\Controllers'], function($app){
$app->get('article','ArticleController@index');
$app->get('article/{id}','ArticleController@getArticle');
$app->post('article','ArticleController@createArticle');
$app->put('article/{id}','ArticleController@updateArticle');
$app->delete('article/{id}','ArticleController@deleteArticle');
});

Run and test your api project on your local server using curl or i recomend you to use postman in chrome. Try in many method like get, post, put and delete.

example to get all article just type http://localhost/api/v1/article and set get method in your post man, it will return all article data in json format if you have already insert data before.

don’t forget to put id of article, if you want to request get 1 article, or update (put) and delete article ( single article )

if you want to add new article, simply you just need to fill the parameter title,content and author data that you want to add into database.

Installing Homestead in Mac OS X

Homestead is the simple way that YOU, code artisan want to build your project in your local computer and you want have setting of your local computer same as your production server. Here is Homestead come to you.

Homestead is a vagrant box that laravel special build for simplify developer work.

First of all you need to download and install Virtualbox and Vagrant before installing Homestead in your local computer.

Step 1 Installing composer

~> curl -sS https://getcomposer.org/installer | php
#!/usr/bin/env php
All settings correct for using Composer
Downloading...

Composer successfully installed to: /Users/you/composer.phar
Use it: php composer.phar

once you have composer.phar downloaded, make it globally

~> sudo mv composer.phar /usr/local/bin/composer

add alias for composer in ~/.bash_profile

alias composer="php /usr/local/bin/composer.phar"

checking composer version

~> composer --version
Composer version 1.0-dev (b23a3cd36870ff0eefc161a4638d9fcf49d998ba)\
2014-11-21 17:59:11

Step 2 Adding ssh keys

check in your local computer if there is already ssh keys usually in ~/.ssh directory. If there is 2 files id_rsa and id_rsa.pub you don’t need to generate ssh keys again.

If you don’t see both files, you can generate it.

~> ssh-keygen -t rsa -C "your@email.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/you/.ssh/id_rsa):
Created directory '/Users/you/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:

Step 3 Adding Homestead box

~> vagrant box add laravel/homestead
==> box: Loading metadata for box 'laravel/homestead'
    box: URL: https://vagrantcloud.com/laravel/homstead

it take a little while for download the box. If you already download, you can adding this box manually ( i assume that homestead.box file placed in your Download directory)

~> vagrant box add laravel/homestead ~/Download/homestead.box
==> box: Loading metadata for box 'laravel/homestead'
    box: URL: https://vagrantcloud.com/laravel/homstead

Step 4 Installing Homestead

~> composer global require "laravel/homestead=~2.0"
Changed current directory to /home/you/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing symfony/process (v2.5.7)
    Loading from cache

  - Installing symfony/console (v2.5.7)
    Loading from cache

  - Installing laravel/homestead (v2.0.7)
    Loading from cache

Writing lock file
Generating autoload files
  • updating you PATH in ~/.bash_profile
    export PATH="~/.composer/vendor/bin:vendor/bin:$PATH"

save and then reload using:

    ~> source ~/.bash_profile
  • Initializing Homestead
    ~> homestead init
    Creating Homestead.yaml file...
    Homestead.yaml file created at: /home/you/.homestead/Homestead.yaml

there is generate 3 files in ~/.homestead/ directory in your local computer. Go to ~/.homestead            directory and edit Homestead.yaml

---
ip:"192.168.10.10"
memory: 2048
cpus:1
authorize: ~/.ssh/id_rsa.pub
keys: - ~/.ssh/id_rsa
folders: - map: ~/Code
           to: /home/vagrant/Code
sites: - map: homestead.app
         to: /home/vagrant/Code/Laravel/public
databases: - homestead
variables: - key: APP_ENV
value: local

note:

  • folders : map-> here is your local directory that you want to share with VM ( usually it as /public_html directory). to -> here is in vm directory that linking your /public_html directory
  •  sites : map -> local domain to point your project. to-> project directory in vm that consist file of your project

in this example i use /Code directory as my public_html directory, you can create ~/Code directory before (do in your local computer) .

Step 5 Adding Local Domain

edit your /etc/hosts file to point your local domain and homestead IP

192.168.10.10 homestead.app

Step 6 Bringing Up Homestead

~>homestead up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'laravel/homestead'...
==> default: Matching MAC address for NAT networking...
==> default Checking if box 'laravel/homestead' is up to date...

you can log on to homestead using

~>homestead ssh
Welcome to Ubuntu 14.04.1 LTS (GNU/Linux 3.13.0-11-generic x86_64)

 * Documentation:  https://help.ubuntu.com/

Step 7 Installing Laravel

go to your public_html ( /Code ) directory in your local computer and then type:

~> composer global require "laravel/installer=~1.1"
Changed current directory to /Users/you/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing guzzlehttp/streams (2.1.0)
    Downloading: 100%

  - Installing guzzlehttp/guzzle (4.2.3)
    Downloading: 100%

  - Installing laravel/installer (v1.1.3)
    Downloading: 100%

Writing lock file
Generating autoload files

Step 8 Checking in Browser

go to your favorite browser and type your local domain  homestead.app for checking if Laravel success installed in our homestead box .

 

 

Modify length of word in the_excerpt function wordpress

Default length of words in the_excerpt function wordpress is 55 words . How to modify it ? when you think it is too long or you want more words to display it ?

– Adding this function in wp-includes/formatting.php

function string_limit_words($string, $word_limit)
{
$words = explode(‘ ‘, $string, ($word_limit + 1));
if(count($words) > $word_limit)
array_pop($words);
return implode(‘ ‘, $words);
}

– add this line in templates page that you want to display the_excerpt

<?php $excerpt = get_the_excerpt(); echo string_limit_words($excerpt, n); ?>

: number of word that you want to display .

Installing Package in Sublime Text

Sublime text is one of my favorite IDE. After entering license a week ago , i will share here how to installing package in sublime text.

  1. select Preferences > Browse Package
  2. see the location of package that your sublime text installed
  3. download package control for sublime and put in package directory
  4. Restart sublime

For Installing package :

  1. press Ctrl ( command ) + Shift + P . type Package Controll : Install Package
  2. scroll down , choose what type of package that you want to install . ex : html5
  3. wait until installation process done.

this is some references package that might be needed http://www.sitepoint.com/10-essential-sublime-text-plugins-full-stack-developer/

Tech reSolution in 2014

Self.Happy_NewYear()

in this year , i will adding some Wish List for improving my skills . Hmmm wait ….. another wish list here , not for fashion or gadget as usual i think . I called it Tech reSolution .

1. Learn Django for some Fun

office hours i’am doing office job as web developer ( not sure , i’am only data entry ) LoL :)) , in the night for lullabies i’am doing some stuff for FUN by learning Django . I wish , it will be little impact for my life :)

2. Learn JS

I think , i’am too bad in JS :(     for some project, it is requirement .

3. Deeping API to be Real Back End Developer

Not Sure i’am a back end developer ? i don’t want to be full stack programmer surely :(

4. reSIGN
LoL :))