Laravelでindexを作成、追加する方法

Schma::create('books', function(Blueprint $table){
	$table->increments('id');
	$table->string('title')->index();
	$table->string('isbn')->unique();
	$table->integer('price');
	$table->integer('author_id');
	$table->timestamps();
});


Schema::table('books', function(Blueprint $table){
	$table->index('title');
});

Schema::table('author_book', function(Blueprint $table){
	$table->index(['author_id', 'book_id']);
});

$table->dropIndex('books_title_index');

league/flysystem-aws-s3-v3

LaravelのファイルストレージとS3を連携させるには、専用のパッケージを導入する必要があるとのこと。

composer.json

"require": {
        "php": "^7.1.3",
        "barryvdh/laravel-dompdf": "^0.8.4",
        "fideloper/proxy": "^4.0",
        "laravel/framework": "5.8.*",
        "laravel/tinker": "^1.0"
    },

ここに、league/flysystem-aws-s3-v3を追加する。

laravel/config/filesystem

's3' => [
            'driver' => 's3',
            'key' => env('AWS_ACCESS_KEY_ID'),
            'secret' => env('AWS_SECRET_ACCESS_KEY'),
            'region' => env('AWS_DEFAULT_REGION'),
            'bucket' => env('AWS_BUCKET'),
            'url' => env('AWS_URL'),
        ],

env(${})となっているので、.envファイルで編集します。

AWS_KEY=[アクセスキー]
AWS_SECRET=[シークレットキー]
AWS_REGION=[リージョン(東京ならap-northeast-1)]
AWS_BUCKET=[バケット名]

そういうことかー

PHPMDを使おう

まずtestコードを書きます。

class Test {

	private $t = 1;

	public function test(){
		echo $this->t;
		$test = 2;
	}
}

で、テストします。

[vagrant@localhost app]$ vendor/phpmd/phpmd/src/bin/phpmd test.php text unusedcode,naming
/home/vagrant/local/app/test.php:5 Avoid variables with short names like $t. Configured minimum length is 3.
/home/vagrant/local/app/test.php:7 Classes should not have a constructor method with the same name as the class
/home/vagrant/local/app/test.php:9 Avoid unused local variables such as ‘$test’.

ぎゃあああああああああああああああああああああ
修正します。

class Test {

	private $test1 = 1;

	public function index(){
		echo $this->test1;
		$test2 = 2;
		echo $test2;
	}
}

で、再度テストすると。。
[vagrant@localhost app]$ vendor/phpmd/phpmd/src/bin/phpmd test.php text unusedcode,naming

おおおおおおおおお、こういうことか~

phpmdを使おう

composerを入れます。

[vagrant@localhost test]$ curl -sS https://getcomposer.org/installer | php
All settings correct for using Composer
Downloading…

Composer (version 1.8.6) successfully installed to: /home/vagrant/local/app/test/test/composer.phar
Use it: php composer.phar

[vagrant@localhost test]$ ls
composer.phar

https://phpmd.org/download/releases/index.html
あれ、アクセスできない??
とりあえず2.0を入れてみます。
# php composer.phar require “phpmd/phpmd=~2.0”

phpmd/phpmd

composer require phpmd/phpmd

What is phpmd?
->It points out potential bugs, suboptimal code, complex expressions, unused parameters, methods, and properties.

About rulesets
The rule set that can be sepecified by PHPMD is as follows.

Clean code rule: cleancode
will point out about the dirty code.

Code size rule: codesize
Attempts to reduce code size by splitting if there are too many methods or large classes.

Discussion rule: controversial
Point out to use the camel case about the camel case and snake case that are often regarded as a problem in developing with PHP

Design rules:
Design issues that are related to software design.

Naming rule: naming
Point out long names, conversely short names etc.

Unused code rule: unusedcode
Find and point out unused code.

shell, perlとphpの比較演算子

Perl
———————————
数値比較
> : より大きい
>= : より大きいか等しい
< : より小さい <= : より小さいか等しい == : 等しい != : 等しくない <=> : 比較

文字列比較
gt: より大きい
ge: より大きいか等しい
lt: より小さい
le: より小さいか等しい
eq: 等しい
ne: 等しくない
cmp: 比較

PHP
———————————
== : 等しい
=== : 同じ
!= : 等しくない
!=== : 同じでない
> : より大きい
< : より小さい >= : 以上
<= : 以下 <=> : より小さい等しいより多き

ん?なんだこの<=>って??あんまり見ないけど。

Shell
———————————
eq : equal to
ge : greater than or equal to
gt : greater than
le : less than or equal to
lt : less than
ne : not equal to

シェルは文字列か。なんか注意が必要ですな

PHPUnit

Using PHPUnit does not mean that you can test any source code. You should have designed your classes to be easy to test. Also, there are places where you can not put them into Unit test even if you have designed that way. If you can not put in the Unit test, you must divide it. Rather, how much code can I put in a unit test?

Unit test here refers to “method-only test” and “class-only test”.

object
setting value
external system(DB, API, file, command)
We separate those “dense dependencies” and “design the class”, “implement the class” and “make a test of the class”. “Dense dependence” refers to, for example the following.

The method using the object directly news the object(depends on the object)
Directly reference configuration files(file_get_contents, json_decode) in logic(depends on file system)
Where file(file_put_contents) directly in logic(depends on file system)
Peek directly into DB(mysqli, PDO) in logic(depends on network and database)
Direct API(file_get_contents, curl) in logic(depends on network and API)
Hit command(system) directly in logic(depends on OS)

namespace UnitTest\Sample;

class Hoge {
	protected $settings = null;
	protected $fileManager = null;
	protected $dbManager = null;
	protected $apiManger = null;
	protected $commandManager = null;

	public function __construct (
		$settings,
		$fileManager,
		$dbManager,
		$apiManager,
		$commandManager){

		$this->settings = $settings;
		$this->fileManager = $fileManager;
		$this->dbManager = $dbManager;
		$this->apiManager = $apiManager;
		$this->commandManager = $commandManager;
		}
}
namespace UnitTest\Sample;
class DatabaseSession
{
		private $connection = null;
		public function __construct($connection)
		{
				$this->connection = $connection;
		}

		public function save($tableName, $object)
		{
				if(!$tableName || !is_scalar($tableName)|| !$object){
						throw new \InvalidArgumentException('$tableName or $object is empty or invalid type');

				}
				if(is_object($object) && $object instanceof \stdClass){
						$ojbect = (array)$object;
				}

				if(!is_array($object)){
						throw new \InvalidArgumentException('$object must be array or \stdClass');
				}

				$values = array_values($object);
				$tableName = '`' . str_replace('`', '\\`', $tableName).'`';
				$columnBlock = implode(',', array_map(function($col) {return '`' . str_replace('`', '\\`',  $col) . '`';}, array_keys($object)));
		        $valueBlock  = implode(',', array_map(function($val) {return '?'; }, $values));
		        $valueMarker = implode('', array_map(function($val) {return strval(intval($val)) === strval($val) ? 'i' : 's'; }, $values));
		        $stmt = $this->connection->prepare("REPLACE INTO $tableName ($columnBlock) VALUES ($valueBlock);");
		        array_unshift($values, $valueMarker);
		        $pointer = array();
		        foreach($values as $key => $val){
		        	$pointer[$key] = &$val;
		        }
		        call_user_func_array(array($stmt, 'bind_param'), $pointer);
		        $stmt->execute();
		        $stmt->close();
		}	
}

Transfer file to confirmation screen

index.php

<form action="confirm.php" enctype="multipart/form-data" method="post">
...

<p>
								職務経歴書<br>
								<label><input id="select-file" style="display:none" type="file" name="filename" onChange="file_selected()"><input id="file-name" type="text" value="ファイルを選択してください" readonly="readonly" onclick="file_select()"></label><span id="message">選択されていません</span>
							</p>
...
<p>
								「<a href="privacy.php">個人情報の取り扱い</a>」に同意の上、無料登録するのボタンをクリックしてください。
								<input type="submit" id="regist" value="同意して無料登録する">
							</p>
						</form>

confirm.php

 $upload = './cfile/'.$_FILES['filename']['name'];
 if(move_uploaded_file($_FILES['filename']['tmp_name'],$upload)){
 	echo 'success';
 } else {
 	echo 'failed';
 }

successed

delete temporary file before upload.

 $dir = glob('./cfile/*');
 foreach($dir as $file){
 	unlink($file);
 }
 $upload = './cfile/'.$_FILES['filename']['name'];
 if(move_uploaded_file($_FILES['filename']['tmp_name'],$upload)){
 	echo 'success';
 } else {
 	echo 'failed';
 }

– If this is done, the uploaded file will disappear when multiple users operate, so it has to be deleted by cron batch etc.

 $upload = './cfile/'.date("YmdHis").$_FILES['filename']['name'];
 if(move_uploaded_file($_FILES['filename']['tmp_name'],$upload)){
 	echo 'success';
 } else {
 	echo 'failed';
 }

PHP file upload process

Let’s upload the file while looking at the simplest code.

test.php

<form action="test2.php" enctype="multipart/form-data" method="post">
	<input name="file_upload" type="file">
	<input type="submit" value="upload">
</form>

test2.php

	$upload = './'.$_FILES['file_upload']['name'];
	if(move_uploaded_file($_FILES['file_upload']['tmp_name'], $upload)){
		echo 'upload success';
	} else {
		echo 'upload failed';
	}

well done.