Yi Yang's blog

  • Home

  • Archives

Javascript-array-conclusion

Posted on 2017-06-28 | Edited on 2019-03-22

A simple conclusion about array. This article was wrote in Chinese

数组

ECMAscript提供了让数组类似于其他数据结构的方法

栈方法 stack

栈是LIFO LAST IN FRIST OUT

提供的方法:

  • push()
    接受任意数量的参数, 向数组末尾添加元素, return value:修改后的数组的长度
  • pop()
    移除数组最后一项,并修改数组长度,return value:移除的元素
Read more »

vue-simple-toaster

Posted on 2017-06-18 | Edited on 2019-03-22

Last week, I created a Vue.js plugin called ‘vue-simple-toaster’.

Address: https://github.com/Yanniyiyi/vue-simple-toaster

vuenews-practice

Posted on 2017-06-16 | Edited on 2019-03-22

Last week, I created a news applicaiton by using Vue.js and ElementUI

Install Vue

Install Vue.js by using the cli.

See the document here

Install ElementUI

Install ElementUI. See the document here

Apply an API key from News API

Apply from here

Install Vue-axios

Vue-axios is a tool for sending get request in our application.

Follow the document here

Install vue-lazyload

A Vue.js plugin for lazyload your Image or Component in the application.

Install from here

Install Vuex

Vuex is a state management pattern + library for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion. It also integrates with Vue’s official devtools extension to provide advanced features such as zero-config time-travel debugging and state snapshot export / import.

Read more »

Create a simple loading bar using Javascript

Posted on 2017-06-13 | Edited on 2019-03-22

This article is about how to create a simple loading bar. Actually, the loading progress of a page could be got. But in this article, I only use a simple way to implement the loading bar.

Prepare

First, create a html file. Like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Js loading bar</title>
</head>
<body>
<div id="progress-container">
<div class="progress-bar" id="progress-bar">

</div>
</div>
</body>
</html>
Read more »

Single Page Application Login (Vuejs)

Posted on 2017-06-05 | Edited on 2019-03-22

In a normal login progress, a solution is:

  1. Check login status, when user enters a page or when the router changes ( the value stored in cookie or local storage)
  2. If we find login status, then we can get the user information.
  3. Otherwise, redirect the user to login page
  4. In login page, validate user input.
  5. Send login request
  6. If not success, the return a error response to user.
  7. If success, get information and save the login status
  8. When a user logout, delete login information

Now, install the vue-cli first by command

1
2
3
4
5
6
7
8
# install vue-cli
$ npm install --global vue-cli
# create a new project template based on webpack
$ vue init webpack my-project
# install dependencies
$ cd my-project
$ npm install
$ npm run dev
Read more »

secret-of-the-javascript-ninja-exercise-answers

Posted on 2017-05-29 | Edited on 2019-03-22

This article is used to record the exercise answers of the book Secrets of the Javascript Ninja-Manning

Chapter 2

  1. What are the twp phases in lifecycle of a client-side web application?

    The two phases in the lifecycle of a client-side web application are page building and even handling.

    In the page building phase, the user interface of our page is built by processing the HTML code, which is a blueprint of the DOM (Document Object Model) and by exectuing main line JavaScript code. In this phase, the processing of HTML code will be paused when the browser meet the <script> tag, instead the browser will try to run the Javascript code.

    After the last HTML node is processed, the page enters the event-handling phase, in which various events are processed through event loop.

  2. What is the main advantage of using the addEventListener method to register an event handler versus assigning a handler to a specific element property?

    When assigning event handler to a specific element property, we can only register one event handler; addEventListener allows us to register as many event handlers as we necessary.

  3. How many events can be processed at once?

    Javascript is based on a single-threaded execution model, in which events are processed one at a time.

  4. In what order are events from the event queue processed

    Events are processed in the order in which they were generated: first in , first out. Just like the queue.

Read more »

4.2 Database and Eloquent

Posted on 2017-05-28 | Edited on 2019-03-22

Introduction to Elquent

Eloquent is an ActiveRecord ORM. It’s a database abstraction layer that provides a single interface to interact with multiple database types.

Creating and Defining Eloquent Models

First, we can create a model like this:

1
php artisan make:model User

This is what we’ll get in app/User.php

1
2
3
4
5
6
<?php
use Illuminate\Database\Eloquent\Model;
class User extends Model
{

}

If you want to automatically create a migration when you create the model, pass -m or –migration flag

1
php artisan make:model User -m

Table name

The default behavior for the table names is that Laravel ‘snake cases’ and pluralizes your class name, so SecondaryUser will access a table named secondary_users.

If you want to customize the name, set the $table property on the model:

1
protected $table = 'users_secondary';

Primary key

Laravel assumes, by default, each table will have an autoincrementing integer primary key, and it will be named id

If you want to customize the name of primary key, change the $primaryKey property

1
protected $primaryKey = 'contact_id';

And if you want to set it to be nonincrementing, use

1
public $incrementing = false;

Timestamps

Eloquent expects every table to have created_at and updated_at timestamp columns. If your table wont’ have them, disable the $timestamps functionality

1
public $timestamps = false;

Retrieving Data with Eloquent

Read more »

4.1 Database and Eloquent

Posted on 2017-05-27 | Edited on 2019-03-22

Laravel provides a suite of tools for interacting with your application’s database, but the most notable is Eloquent.

Configuration

To config the database access, we need to go to config/database.php.

Migrations

Laravel makes it easy to define your database structure with code-driven migrations. Every new table, column, index, and key can be defined in code.

Defining Migrations

A migration is a single file that defines two things: the modifications desired when running this migration up and the modifications desired when running this migration down

The Laravel’s default ‘create user table’ migration

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUserTable extends Migration
{
public function up(){
Schema::create('users',function(Blueprint $table){
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password',60);
$table->rememberToken();
$table->timestamps();
});
}

public function down(){
Schema::drop('users');
}
}

up() method tells the migration to create a new table called users with a few fields, and down() method tells it to drop the users table

Create a migration

There’s an Artisan command for creating a migration file.

1
php artisan make:migration

The command has a parameter, which is the name of the migration. For example if you want to create a ‘create users table’ migration, you can run this:

1
php artisan make:migration create_users_table

There are two flags we can optionally pass to this command. --create=table_name prefills the migration with code designed to create a table named table_name, and --table=table_name just prefills the migration for modifications to an existing table.

1
2
php artisan make:migration create_users_table --create=users
php artisan make:migration add_votes_to_users_table --talbe=users

Creating tables

In migration file, the migrations depend on the Schema facade and its methods.

To create a new table in a migration, use the Schema‘s create() method

1
2
3
Schema::create('table',function(Blueprint $table){

})

The first parameter is table’s name, and the second method closure that defines its columns.

Creating columns

To create new columns in a table, whether in a create table call or a modify table call, use the instance of Blueprint that’s passed into the second closure.

1
2
3
Schema::create('table',function(Blueprint $table){
$table->string('name');
})

Blueprint has a lot of methods for us to create different type of columns

For more details, check Laravle’s available column types

Building extra properties fluently

Most of the properties of a field definition, for example, the length are set as teh second parameter of the field creation method. We can chain more method calls after the creation of the column.

1
2
3
Schema::table('users',function(Blueprint $table){
$table->string('email')->nullable()->after('last_name');
});

In above code, we defined a nullable column called email and this column is placed right after ‘last_name’ column.

Droping tables

1
Schema::drop('users');

Modifying columns

To modify a column, just write the code we would write to create the column as if it were new, and then append a call to the change() method after it.

So if we have a string column named name that has a length of 255 and we want to change its length to 100, this is how we would write it:

1
2
3
Schema::table('users', function(Blueprint $table){
$table->string('name',100)->change();
});

How to rename a column

1
2
3
Schema::table('users', function(Blueprint $table){
$table->renameColumn('from','to');
});

How to drop a column

1
2
3
Schema::table('users',function(Blueprint $table){
$table->dropColumn('name');
});

Adding indexes

1
2
3
4
5
6
$table->primary('id'); // primary key: unnecessary if used increments()
$table->primary(['first_name','last_name']); // composite keys
$table->unique('email'); // unique index
$table->unique('email','optional_custom_index_name');
$table->index('amount'); //basic index
$table->index('amount','optional_custom_index_name'); //basic index

Note: primary() is not necessary if you are using the increments() meth

od to create your index, this will automatically add a primary key index for you

Removing indexes

1
2
3
$table->dropPrimary('id');
$table->dropUnique('email');
$table->dropIndex('optional_custom_index_name');

Adding and removing foreign keys

To add a foreign key that a particular column references a column on another table

1
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

To remove foreign key

1
$table->dropForeign(['user_id']);

Running Migration

Read more »

3. Collecting and Handling User Data

Posted on 2017-05-26 | Edited on 2019-03-22

Laravel provides a collection of tools for gathering, validating, normalizing. and filtering user-provided data.

Injecting a Request Object

The common tool for accessing user data in Laravel is injecting an instance of the Illuminate\Http\Request object. It provides easy access to all of the ways users can provide input to our sites: POST, posted JSON, GET, and URL segments.

1
2
3
Route::get('form', function(Illuminate\Http\Request $request){

})

$request->all()

$request->all() returns an array containing all of the input the user has provided, from every source.

Let’s say we have a form POST to a URL with a query parameter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<form method="post" action="/post-route?utm=12345">
{{ csrf_field() }}
<input type='text' name='firstName'>
<input type='submit'>
</form>

Route::post('post-route', function (Request $request){
var_dump($request->all());
});

// Outputs:
/**
* [ '_token' => 'your csrf token',
* 'firstName' => 'value',
* 'utm' => 12345
* ]
**/

$request->except() and $request->only()

$request->except() allows you to choose one or more fields to exclude, for example the ‘_token’ filed

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<form method="post" action="/post-route?utm=12345">
{{ csrf_field() }}
<input type='text' name='firstName'>
<input type='submit'>
</form>

Route::post('/post-route', function (Request $request){
var_dump($request->except('_token'));
});

// Outputs:
/**
* [
* 'firstName' => 'value',
* 'utm' => 12345
* ]
**/

$request->only() is the inverse of $request->except()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<form method="post" action="/post-route?utm=12345">
{{ csrf_field() }}
<input type='text' name='firstName'>
<input type='submit'>
</form>

Route::post('/post-route', function (Request $request){
var_dump($request->only(['firstName','utm']));
});

// Outputs:
/**
* [
* 'firstName' => 'value',
* 'utm' => 12345
* ]
**/

$request->has() and $request->exists()

$request->has() and $request->exists()could detect whether a particular piece of user input is available to you. The difference is that has() returns FALSE if the key exists and is empty; exists() returns TRUE if the key exists, even if it’s empty.

request->input()

request->input() allows you to get the value of just a single field.

1
2
3
Route::post('/post-route', function(Request $request){
$userName = $request->input('name','(anonymous)');
});

The second parameter is the default value, so if the user hasn’t passed in a value, you can have a sensible fallback.

Array Input

Laravel also provides convenience helpers for accessing data from array input.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<form method='post' action='/post-route'>
{{ csrf_field() }}
<input type='text' name='employees[0][firstName]'>
<input type='text' name='employees[0][lastName]'>
<input type='text' name='employees[1][firstName]'>
<input type='text' name='employees[1][lastName]'>
</form>

Route::post('/post-route', function(Request $request){
$employeeZeroFirstName = $request->input('employees.0.firstName');
$allLastNames = $request->input('employees.*.lastName');
$employeeOne = $request->input('employees.1');
})

// If forms filled out as "Jim" "Smith" "Bob" "Jones":
// $employeeZeroFirstName = 'Jim';
// $allLastNames = ['Smith', 'Jones'];
// $employeeOne = ['firstName' => 'Bob', 'lastName' => 'Jones']

From Request

Read more »

2. Blade templating

Posted on 2017-05-24 | Edited on 2019-03-22

Laravel offers a custom templating engine called Blade.

Echoing Data

is functionally equivalent to <?= htmlentities($variable) ?>. If you want to echo without the escaping, use {!! and !!}.

Note: the difference between and {!! $variable !!}

Let’s say we have a route

1
2
3
4
Route::get('/', function () {
$test = '<span>hello world</span>';
return view('welcome',compact('test'));
});

And in your welcome blade view

1
2
{{ $test }}  // it will show <span>hello world</span>
{!! $test !!} // this will show hello world only, the <span> is treated as a part of html page
1
2
3
4
5
6
// Parsed as Blade; the value of $bladeVariable is echoed to the view 
{{ $bladeVariable }}

// @ is removed, and "{{ handlebarsVariable }}" echoed to the view
// directly
@{{ handlebarsVariable }}

Control Structures

Conditionals

@if

Syntax

1
2
3
4
5
6
7
@if(count($users) === 1)
There is one user
@elseif(count($users) === 2)
There are two users
@else
There are {{count($users)}} users
@endif

@unless

Syntax: @unless condition is the same as <?php if(!$condition) ?>

1
2
3
@unless(count($users) > 0)
No users
@endunless

Loops

@for

1
2
3
@for( $i = 0; $i < $users->slotsCount(); $i++ )
{{ $i }}
@endfor

@foreach

1
2
3
@foreach($users as $user)
{{$user->name}}
@endforeach

@while

1
2
3
@while( $user = array_pop($users) )
{{$user->name}}
@endwhile

@forelse

1
2
3
4
5
@forelse($users as $user)
{{ $user->name }}
@empty
No users
@endforelse

$loop within @foreach and @forelse

Within a @foreach or @forelse loop, Laravel provides a $loop variable, it will return a stdClass object with the following properties:

index

The 0-based index of the current item in the loop; 0 would mean ‘first item’

iteration

The 1-based index of the current item in the loop; 1 would mean ‘first itme’

remaining

How many items remain in the loop, if the current item is the first of three, this will be 2

count

The count of items in loop

first

A boolean indicating whether this is the first item in the loop

last

A boolean indicating whether this is the last item in the loop

depth

How many levels deep this loop is: 1 for a loop, 2 for a loop within a loop

parent

Refers to the $loop variable for the parent loop item; if this loop is within another @foreach loop otherwise, null

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<ul>
@forelse( $users as $user)
There are {{$loop->count}} users.
<li> {{ $loop->iteration }}: {{ $user->name }}
@if($user->hasChildren())
<ul>
@foreach($user->children() as $child)
<li>{{ $loop->parent->iteration }}.
{{ $loop->iteration }}:
{{ $child->name }}
</li>
@endforeach
</li>
@empty
No users
@endforelse
</ul>

or

If you are not sure a variable is set or not, use or can set a default value.

1
{{$title or 'Default Title'}} // if $title is not set, 'Default title' will be echoed.

Template Inheritance

Read more »
123

Yi Yang

22 posts
10 tags
© 2019 Yi Yang
Powered by Hexo v3.8.0
|
Theme – NexT.Muse v7.0.1