20210410のPHPに関する記事は14件です。

初学者がLaravelを学び始める1

はじめに ララベルでアプリにアクセスし処理を行うにはアドレスと処理を関連づけるルーティングと全体の制御を行うコントローラーが必要となる。 ルーティング 一般的なウェブサイトではwebサーバーの公開フォルダの中にファイルを用意しておくとそのままファイルが表示されます。例えばwebappというフォルダにhelo.htmlと言うファイルを用意すれば、http://〇〇/webapp/helo.htmlというアドレスにアクセスすると自動的にそのファイルが読み込まれ表示されます。 しかしLaravelを使っている場合はそうはできません。 Laravelでは特定のアドレスにアクセスされるとそのアドレスに割り振られたプログラムが実行されそれによって必要な処理や画面が表示されます。 このような〇〇アドレスにアクセスした場合に✖️✖️という処理を行うというのがルーティングです。 routesフォルダについて web.phpのファイルは一般的なwebページにアクセスするためのルーティングです。 基本的にwebページに後悔するものは全てこのweb.phpにルート情報を記述すると考えてよい。(当分の間はそれ以外のファイルは使用しない。) ルート情報の記述 <?php Route::get('/', function () { return view('welcome'); }); このようにweb.phpに書かれていた場合ですが 今回はトップページにアクセスした際の処理を記述しています。Laravelのアプリではデフォルトでトップページの処理が記述されています。 ルートの基本情報の見方ですが Route::get('アドレス', 関数など ); というふうになっています。 第一引数には割り当てられるアドレス、第二引数には処理を指定します。 ちなみに第二引数には関数以外にもコントローラーを指定することもあります。 getを使ってアドレスと処理を割り当てることがルートの情報設定の基本です。 トップページのルート情報 今回は第二引数には関数を指定しておりますが、引数なしの無名関数(グロージャ関数)となっております。 内部ではreturnで戻り値を指定しておりここで返される戻り値がそのアドレスにアクセスした際に表示される内容となります。ここではviewという関数を使って戻り値を用意しています。これは以下のように使用します。 view(テンプレート名) このviewは指定されたテンプレートファイルをロードしてレンダリングして返すという役割があリます。 要するに今回はwelcomeとあるのでwelcomeのviewが表示されることになります。(正確にはwelcome.blade.php) また、基本的にビューはHTMLのコードが書かれているように見えますが@マークから始まるような文も多く存在します。 これはbladeと呼ばれるテンプレートエンジンをつかて書かれたソースコードです。 ララベルではPHPをそのまま使ってウェブページを作ることもできますが、bladeテンプレートエンジンを使うことの方が多いです。 簡単に仕組みを解説するとviewフォルダの中にテンプレートファイルが用意され、それをview関数で読み込んで表示しているということになります。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

PHPの標準関数をRubyで書く(文字列操作編)

はじめに PHPの標準関数をRubyで書いてみました。 簡単に書けそうなものだけパズル感覚で書いてます。 文字列操作編です。 引数と返り値の型はテーブルで記載しました。 str_contains($haystack, $needle) PHP: str_contains - Manual haystack String needle String return TrueClass | FalseClass Ruby haystack.include?(needle) str_ends_with($haystack, $needle) PHP: str_ends_with - Manual haystack String needle String return TrueClass | FalseClass Ruby haystack.end_with?(needle) str_getcsv ($string, $separator, $enclosure, $escape) PHP: str_getcsv - Manual string String separator String enclosure String escape 標準CSVライブラリでは指定不可(2回続けて入力してエスケープ) return Array<String> Ruby require "csv" CSV.parse_line(string, col_sep: separator, quote_char: enclosure) str_ireplace($search, $replace, $subject, &$count) PHP: str_ireplace - Manual search String replace String subject String count Integer return String Ruby count = 0 subject.gsub(Regexp.new(Regexp.escape(search), Regexp::IGNORECASE)) {count += 1; replace} str_pad($string, $length, $pad_string, $pad_type) PHP: str_pad - Manual string String length Integer pad_string String pad_type STR_PAD_RIGHT return String Ruby string.ljust(length, pad_string) string String length Integer pad_string String pad_type STR_PAD_LEFT return String Ruby string.rjust(length, pad_string) string String length Integer pad_string String pad_type STR_PAD_BOTH return String Ruby string.center(length, pad_string) str_repeat($string, $times) PHP: str_repeat - Manual string String times Integer return String Ruby string * times str_replace($search, $replace, $subject, &$count) PHP: str_replace - Manual search String replace String subject String count Integer return String Ruby count = 0 subject.gsub(Regexp.new(Regexp.escape(search))) {count += 1; replace} str_rot13($string) PHP: str_rot13 - Manual string String return String Ruby string.tr("a-zA-Z", "n-za-mN-ZA-M") str_shuffle($string) PHP: str_shuffle - Manual string String return String Ruby string.chars.shuffle.join str_split($string, $length) PHP: str_split - Manual string String length Integer ※1以上 return String Ruby string.each_char.each_slice(length).map(&:join) str_starts_with($haystack, $needle) PHP: str_starts_with - Manual haystack String needle String return TrueClass | FalseClass Ruby haystack.start_with?(needle) str_word_count($string, $format, $characters) PHP: str_word_count - Manual string String format 0 characters String return Integer Ruby string.match(/^[-']*(.*?)-*$/)[1].scan(/[-'a-zA-Z]+/).count string String format 1 characters String return Array<String> Ruby string.match(/^[-']*(.*?)-*$/)[1].scan(/[-'a-zA-Z]+/) strcasecmp($str1, $str2) PHP: strcasecmp - Manual str1 String str2 String return Integer Ruby str1.casecmp(str2) ※返却値は-1, 0, 1のいずれかなので注意 strcmp($str1, $str2) PHP: strcmp - Manual str1 String str2 String return Integer Ruby str1 <=> str2 ※返却値は-1, 0, 1のいずれかなので注意 strcspn($string, $characters, $offset, $length) PHP: strcspn - Manual string String characters String offset Integer length Integer ※0以上 return Integer Ruby string = string[offset, length] string.chars.each_with_index.find { |c, _| characters.include?(c) }&.at(1) || string.length stripos($haystack, $needle, $offset) PHP: stripos - Manual haystack String needle String offset Integer return String | FalseClass Ruby haystack.downcase.index(needle.downcase, offset) stristr($haystack, $needle, $before_needle) PHP: stristr - Manual haystack String needle String before_needle FalseClass return String | FalseClass Ruby haystack.chars.each_with_index.find { |c, _| c.casecmp?(needle) }.then { |_, i| i ? haystack[i..] : false } haystack String needle String before_needle TrueClass return String | FalseClass Ruby haystack.chars.each_with_index.find { |c, _| c.casecmp?(needle) }.then { |_, i| i ? haystack[0, i] : false } strlen($string) PHP: strlen - Manual string String return Integer Ruby string.length strncasecmp($str1, $str2, $length) PHP: strncasecmp - Manual str1 String str2 String length Integer return Integer Ruby str1[0, length].casecmp(str2[0, length]) ※返却値は-1, 0, 1のいずれかなので注意 strncmp($str1, $str2, $length) PHP: strncmp - Manual str1 String str2 String length Integer return Integer Ruby str1[0, length] <=> str2[0, length] ※返却値は-1, 0, 1のいずれかなので注意 strpbrk($string, $characters) PHP: strpbrk - Manual string String characters String return String | FalseClass Ruby string.chars.each_with_index.find { |c, _| characters.include?(c) }.then { |_, i| i ? string[i..] : false } strpos($haystack, $needle, $offset) PHP: strpos - Manual haystack String needle String offset Integer return String | FalseClass Ruby haystack.index(needle, offset) strrchr($haystack, $needle) PHP: strrchr - Manual haystack String needle String return String | FalseClass Ruby haystack.chars.reverse.each_with_index.find { |c, _| c == needle.chr }.then { |_, i| i ? haystack[-i-1..] : false } strrev($string) PHP: strrev - Manual string String return String Ruby string.reverse strripos($haystack, $needle, $offset) PHP: strripos - Manual haystack String needle String offset Integer ※0以上 return String | FalseClass Ruby haystack[offset..].downcase.rindex(needle.downcase)&.+(offset) || false haystack String needle String offset Integer ※0未満 return String | FalseClass Ruby haystack.downcase.rindex(needle.downcase, offset) || false strrpos($haystack, $needle, $offset) PHP: strrpos - Manual haystack String needle String offset Integer ※0以上 return String | FalseClass Ruby haystack[offset..].rindex(needle)&.+(offset) || false haystack String needle String offset Integer ※0未満 return String | FalseClass Ruby haystack.rindex(needle, offset) || false strspn($string, $characters, $offset, $length) PHP: strspn - Manual string String characters String offset Integer length Integer ※0以上 return Integer Ruby string = string[offset, length] string.chars.each_with_index.find { |c, _| !characters.include?(c) }&.at(1) || string.length strstr($haystack, $needle, $before_needle) PHP: strstr - Manual haystack String needle String before_needle FalseClass return String | FalseClass Ruby haystack.chars.each_with_index.find { |c, _| c == needle }.then { |_, i| i ? haystack[i..] : false } haystack String needle String before_needle TrueClass return String | FalseClass Ruby haystack.chars.each_with_index.find { |c, _| c == needle }.then { |_, i| i ? haystack[0, i] : false } strtolower($string) PHP: strtolower - Manual string String return String Ruby string.downcase strtoupper($string) PHP: strtoupper - Manual string String return String Ruby string.upcase strtr($string, $from, $to) PHP: strtr - Manual string String from String to String return String Ruby limit = [from, to].map(&:length).min string.tr(from[0, limit], to[0, limit]) strtr($string, $replace_pairs) PHP: strtr - Manual string String replace_pairs Hash<String, String> return String Ruby string.gsub(Regexp.new(replace_pairs.keys.map { |s| Regexp.escape(s) }.join('|'))) { |m| replace_pairs[m] } 参考文献 Class array (Ruby 3.0.0 リファレンスマニュアル). (n.d.). docs.ruby-lang.org. Retrieved March 30, 2021, from https://docs.ruby-lang.org/ja/latest/class/Array.html Class CSV (Ruby 3.0.0 リファレンスマニュアル). (n.d.). docs.ruby-lang.org. Retrieved March 30, 2021, from https://docs.ruby-lang.org/ja/latest/class/CSV.html Class Regexp (Ruby 3.0.0 リファレンスマニュアル). (n.d.). docs.ruby-lang.org. Retrieved March 30, 2021, from https://docs.ruby-lang.org/ja/latest/class/Regexp.html Class string (Ruby 3.0.0 リファレンスマニュアル). (n.d.). docs.ruby-lang.org. Retrieved March 30, 2021, from https://docs.ruby-lang.org/ja/latest/class/String.html Module enumerable (Ruby 3.0.0 リファレンスマニュアル). (n.d.). docs.ruby-lang.org. Retrieved March 30, 2021, from https://docs.ruby-lang.org/ja/latest/class/Enumerable.html Str_contains. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.str-contains.php Str_ends_with. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.str-ends-with.php Str_getcsv. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.str-getcsv.php Str_ireplace. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.str-ireplace.php Str_pad. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.str-pad.php Str_repeat. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.str-repeat.php Str_replace. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.str-replace.php Str_rot13. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.str-rot13.php Str_shuffle. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.str-shuffle.php Str_split. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.str-split.php Str_starts_with. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.str-starts-with.php Str_word_count. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.str-word-count.php Strcasecmp. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strcasecmp.php Strcmp. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strcmp.php Strcspn. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strcspn.php Stripos. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.stripos.php Stristr. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.stristr.php Strlen. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strlen.php Strncasecmp. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strncasecmp.php Strncmp. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strncmp.php Strpbrk. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strpbrk.php Strpos. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strpos.php Strrchr. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strrchr.php Strrev. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strrev.php Strripos. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strripos.php Strrpos. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strrpos.php Strspn. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strspn.php Strstr. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strstr.php Strtolower. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strtolower.php Strtoupper. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strtoupper.php Strtr. (n.d.). PHP: Hypertext Preprocessor. Retrieved March 30, 2021, from https://www.php.net/manual/ja/function.strtr.php
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Docker上のphpMyAdminでアップロード上限が派生したときの解決法

前提 DockerでphpMyAdminのイメージを利用してめでたくphpMyAdminがローカルで利用できるようになっていること。 この記事で解決する問題 インポート機能で大きなサイズのファイルをインポートした時に、次のようなエラーが発生した。 ファイルサイズが PHP の設定で許可された最大値を超えています。 解決方法 概要 php.iniのupload_max_filesizeを修正し、phpMyAdminのファイルアップロー上限を変更する。 docker-compose.ymlで次のようにapacheイメージのphp.iniをvolumeでマウントする web: (中略) volumes: - ./web/php.ini:/etc/php.ini マウントしたphp.iniの upload_max_filesizeを修正する upload_max_filesize = 256M docker-compse.ymlでphpMyAdminのファイルアップロー上限を変更する。 phpmyadmin: (中略) environment: UPLOAD_LIMIT: 256M これで、デフォルトで(最長: 2,048KiB)のところを、256Mまでのファイルをアップロードできるようになります。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

includeとrequireの違い

1つのファイルに共通するコードを書いておき、個別のファイルからそのファイルを読み込んでプログラムを効率的に作成する方法です。 includeとrequire 書き方は、下記のような書き方です。 これはどちらも変わりません。 include 'ファイル名'; include 指定されたファイルが読み込めない場合でも処理を継続します。 require 指定されたファイルが読み込めない場合は処理中止。 include_once すでに同じファイルが読み込まれている場合はincludeを実行しない。 require_once すでに同じファイルが読み込まれている場合はrequireを実行しない。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

MAMP環境のDB接続エラー[SQLSTATE[HY000] [2002] Connection refused]

最近パソコンをMacに変えてMAMP環境で学習しています。 PHPからDBに接続する時、ちょっとハマってしまった点があったのでこちらに忘備録も兼ねて記載しておきます。 PDOの引数 PHPでPDOのオブジェクトを生成してデータベースに接続する際には、引数として以下のように3つ必要です。ちなみにPDOはPHP Data Objectの略でPHPでデータベースを扱うときにオブジェクトになります。 PHP new PDO('接続文字列','ユーザー名','パスワード') XAMPP環境 WindowsではXAMPP環境で以下の記述でデータベースに接続できていました。 PHP <?php try{ $db = new PDO('mysql:dbname=mydb;host=127.0.0.1;charset=utf8','root',''); } catch(PDOException $e) { echo 'DB接続エラー:'.$e->getMessage(); } ?> MacでのDB接続エラー MacでもMAMP環境で同じようにやればいいかなと思い、同じ記述でデータベースに接続してみたところまさかのエラー DB接続エラー:SQLSTATE[HY000] [2002] Connection refused MAMP環境 どうやらMAMP環境ではPDOの引数の記述が違うようで、正しくは以下の通りです。 PHP <?php try{ $db = new PDO('mysql:dbname=mydb;host=localhost;charset=utf8','root','root'); } catch(PDOException $e) { echo 'DB接続エラー:'.$e->getMessage(); } ?> PDO接続文字列のところで、host=に後に続くのがXAMPPでは127.0.0.1なのに対して、MAMPではlocalhostになります。またパスワードがXAMPPでは''(空文字)なのに対して、MAMPでは'root'になってます。これは初期値となっておりこちらも変更しないといけません。 参考書やテキストではXAMPP環境での記述が多いので、MAMP環境で接続エラーになっている人がいたらとりあえずhostをlocalhostに、パスワードをrootにしておけばOKです。 以上!!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Laravel】便利なService(サービス)の使い方を実際に使って理解する。ブレードやコントローラで使う実例。

LaravelのServiceを使うと、Servicesの配下に作成したphpファイルに記述した処理をブレードの中で実行することができる。 @injectディレクティブを使うと超簡単に呼び出せる。 目次 Serviceの用途 ファイルの作成 ブレードで呼び出す方法 コントローラで呼び出す方法 ブレードでifと組み合わせる方法 Serviceの用途 ブレードやコントローラの中で呼び出す関数やプロパティを定義できる。使い方は自由度が高く、例えば以下があげられる。 コントローラの処理をサービスに移行する ルート名によってmeta情報の適用を変更する メール送信用の本文を作成する チャットにメッセージを投げる APIのデータを取得する 仕組みはとても簡単なので、実際に使ってみるとわかりやすい。 1. ファイルの作成 サービスファイルは app > Services 配下に作成する。ファイル名はアッパーキャメルで記載する。 ファイルは冒頭に名前空間namespace App\Services;を記述してからクラスを記述する。 作成例 testServiceというサービスコンテナを作成する。 $ mkdir app/Services $ vi app/Services/testService.php testService.php <?php namespace App\Services; class TestService { public static function test() { return "staticメソッド in TestService"; } public function test1() { return "インスタンスメソッド in TestService"; } } 試しに、staticメソッド(test)とインスタンスメソッド(test1)を作成している。 ・staticメソッドとは、インスタンスを生成せずともクラスから直接呼び出せるメソッド。 ・インスタンスメソッドとは、生成したインスタンスから呼び出せるメソッド。 (参考)PHP staticの使い方と意味 2. ブレードで呼び出す方法 ・@inject( '変数名', 'サービスの名前空間' ) .blade.php @inject ( 'TestService', 'App\Services\TestService' ) これで、作成したサービスを$TestServiceとしてブレード内で呼び出せる。 メソッドの呼び出し PHPのルールに従って、staticメソッドを呼び出す場合はクラス名::メソッド名、インスタンスメソッドはインスタンス名::メソッド名。 @injectで読み込んだ変数はクラスとしてもインスタンス(オブジェクト)としても使える。 .blade.php @inject ( 'TestService', 'App\Services\TestService' ) {{-- staticメソッドの呼び出し --}} <div>{{ $TestService::test() }}</div> {{-- インスタンスメソッドの呼び出し --}} <div>{{ $TestService->test1() }}</div> {{-- --}}はコメントアウト。 ▼ブラウザの表示 サービスに記述した処理を簡単に呼び出すことができた。 3. コントローラで呼び出す方法 コントローラで呼び出す場合は冒頭でuse 名前空間で読み込めば使えるようになる。 Controller.php namespace App\Http\Controllers; use Illuminate\Http\Request; //サービスの読み込み use App\Services\TestService; class UserController extends Controller { public function index(TestService $instance) { //(1)サービスのstaticメソッド呼び出し dump( TestService::test() ); //(2)サービスのインスタンスメソッド呼び出し $obj = new TestService; dump( $obj->test1() ); //(3)サービスのインスタンスメソッド呼び出し(依存注入) dump( $instance->test1() ) return view('user'); } (2)(3)はインスタンスメソッドを呼び出すため、インスタンス(オブジェクト)を生成する必要がある。 (3)は関数の引数の中でクラスをインスタンス化し変数に注入している。依存注入と呼ぶ。 ▼ブラウザの表示 コントローラの中でサービスのメソッドを呼び出せている。 4. ブレードでifと組み合わせる サービスとif文を組み合わせれば、ルート名によってif文で処理を切り分けることも可能。 例えば、ページによってメタタグに渡す値を変更する処理を記述したmetaServiceというサービスを作成する。 中にエラーの場合の処理や、引数を渡した場合の処理などを記述しておくと、ページに合わせてメタ情報を切り替えることができる。 base.blade.php @inject('metaService', 'App\Services\metaService') @php if(isset($exception)){ $meta = $metaService::createMetaForError($exception); }elseif(Route::currentRouteName() === 'blog.show' || Route::currentRouteName() === 'blog.preview'){ $meta = $metaService::createMeta($article); }else{ $meta = $metaService::createMeta(); } @endphp <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"> <meta name="description" content="{{ $meta['description'] }}"> <meta name="keywords" content="{{ $meta['keywords'] }}"> <title>{{ $meta['title'] }}</title> 以下省略,,, サービスの例は以下。 metaService.php <?php namespace App\Services; use LaravelMicresArticle\Services\ItemService; class PageService { public static function createMetaForError($exception):array { $code = $exception->getStatusCode(); if(__('error.' . $code . '.message') === 'error.' . $code . '.message'){ $description = __('page.errors.common.description'); }else{ $description = __('error.' .$code. '.message'); } $meta['title'] = __('page.errors.common.title', ['code' => $code]) . ' | サイト名'; $meta['keywords'] = ' キーワード1, キーワード2 ' . __('page.errors.common.keywords', ['code' => $code]) ; $meta['description'] = $description; return $meta; } //$articleのデフォルト値はnull public static function createMeta($article = null):array { $meta = []; $routeName = \Route::currentRouteName(); $categorySlug = array_key_exists('category_slug', \Route::current()->parameters())? \Route::current()->parameters()['category_slug'] : null; if($categorySlug) $routeName .= '.' . $categorySlug; //title if(__('page.' . $routeName . '.title') === 'page.' . $routeName . '.title'){ $meta['title'] = 'サイト名'; }else{ $meta['title'] = __('page.' . $routeName . '.title') . ' | サイト名'; } //keywords $meta['keywords'] = ' キーワード1, キーワード2 ' . __('page.' . $routeName . '.keywords'); //description $meta['description'] = __('page.' . $routeName . '.description'); //article if(\Route::currentRouteName() === 'blog.show' && $article){ $meta['title'] = $article->title . ' | サイト名'; $meta['keywords'] = 'キーワード1, キーワード2, ' . $article->keywords; $meta['description'] = $article->desc; } return $meta; } 必要に応じて条件分岐や、メソッドを追加することでメンテできる。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【Laravel】php artisan migrateエラーが出た SQLSTATE[HY000] [2054]

今回、php artisan migrateでエラーが出て困ったので投稿します。 SQLSTATE[HY000] [2054] The server requested authentication method unknown 認証方式が知らんとか言われた。どうしよ、、、じゃあMySQLで確認しますか。 mysql> select user, host, plugin from mysql.user; 確認するとrootユーザーのパスワードの認証方式はcaching_sha2_passwordであった。なんかMySQL8.0ではデフォルトでこうなっているらしい??? なので変更しましょう! mysql> alter user 'root'@'localhost' identified with mysql_native_password by 'root'; これで変更して無事実行できました!
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

【PHP・Laravel】クラス内のstaticの意味と使い方まとめ

LaravelなどPHPファイルのクラスの中で使われているstaticという記載の使い方について。 変数(プロパティ)に適用する場合と、メソッドに適用する場合の2パターンがある。 目次 staticの意味 staticはいつ使うか? staticの使い方 アクセス権限の種類 staticプロパティの設定例 staticメソッドの設定例 メソッドを呼び出す時の注意点 staticの意味 静的という意味。 通常クラスの中で定義した変数(プロパティ)やメソッドを呼び出すためにはインスタンスを生成する必要がある。元々存在しないものを生み出すのでこれはdynamic(動的)といえる。 一方、static(静的)では、インスタンスを生成せずクラスを直接指定して、変数やインスタンスを呼び出せるようにできる。(←★超重要) staticはいつ使うか? アプリケーションの中で複数回登場する関数やプロパティを定義するときに使える。 ヘルパーも似た機能だが、ヘルパーの場合は作成したメソッド名をどこでも呼び出せるのに対し、staticはそのクラスを呼び出した場合のみで使える。 プロパティ名やメソッド名が被りそうな場合や、ある特定の目的のプロパティやメソッドをまとめる場合に使うと便利。 (参考)Laravel:ヘルパ関数の作り方 staticの使い方 ・変数への適用 [アクセス権限] static $変数名 = 値; アクセス権限は必須。verで定義した場合はpublicになる。 ・メソッドへの適用 [アクセス権限] static function メソッド名(){}; アクセス権限がない場合はpublicと同じになる。 アクセス権限の種類 アクセス権限は縛りの強い順に以下のようになる。 private :定義したクラス内のみ protected :継承クラス(子クラス)からもアクセス可能 public :クラスの外からアクセス可能 記載なし(function) :publicと同じ 記載なし(プロパティをvarで定義) :publicと同じ staticプロパティの設定例 クラスを直接指定して呼び出した場合 TestClassを作成して、通常のクラスプロパティとstaticプロパティを作成し、それぞれをクラスの外から呼び出してみる。 testClass.php <?php class TestClass{ public $name = "名前"; public static $staticName = "staticな名前"; } //クラスの外で呼び出し echo TestClass::$staticName; staticな名前 echo TestClass::$name; //Warning: Uncaught Error: //Access to undeclared static property: //TestClass::$name in php shell code:1 ・TestClass::$staticName;は値を呼び出すことができた。 ・TestClass::$name;はエラーになった。(インスタンスを生成してないので存在しない) インスタンスを生成して呼び出した場合 今後はインスタンスを生成してそれぞれの値を呼び出してみる。 testClass.php class TestClass{ public $name = "名前"; public static $staticName = "staticな名前"; } //クラスの外でインスタンス生成し呼び出し $test = new TestClass; echo $test->staticName; //(何も表示されない) echo echo $test->name; 名前 ・staticNameはインスタンスの中にないので空。 ・nameはデフォルトの「名前」が呼び出される。 staticメソッドの設定例 メソッドの場合もstaticを付ければクラスの外からインスタンス(オブジェクト)を生成せずに呼び出せる。 testClass.php class TestClass{ public function test(){ echo "インスタンスメソッド"; } public static function testStatic(){ echo "staticメソッド"; } } //メソッドの呼び出し TestClass::testStatic(); //"staticメソッド" TestClass::test(); //インスタンスメソッドの呼び出し $obj = new TestClass; $obj->test(); //インスタンスメソッド メソッドを呼び出す時の注意点 staticメソッドの中でインスタンスプロパティを呼び出すことはできない。 static functionと$this->インスタンスプロパティ名の組み合わせはエラーになる。 NG例 class Static{ public $name = "名前"; public static $staticName = "static名前"; //staticメソッドの中にインスタンスプロパティが入っているとエラーになる。 public function static staticFunc(){ echo self::$staticName; echo $this->name; } } $obj = new Static; $obj->staticFunc(); //Warning: Uncaught Error: //Call to undefined method Dynamic::staticFunc() in php shell code:1 Static::saticFunc(); //Warning: Uncaught Error: //Call to undefined method Dynamic::staticFunc() in php shell code:1 ▼OK事例 メソッドにstaticがなければ、インスタンスプロパティを呼び出せる。 OK class Dynamic{ public $name = "名前"; public static $staticName = "static名前"; public function dynamicFunc(){ echo self::$staticName; echo $this->name; } } $obj = new Dynamic; $obj->dynamicFunc(); //static名前名前 Dynamic::dynamicFunc() //(出力なし・・・staticメソッドが存在しない) ・自分のクラスの中でクラス自身を呼び出す場合はself::を使う。 ・インスタンスプロパティを呼び出す場合はオブジェクトとして$thisを使う。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravelのカスタムファイルシステムを使用してCloudStorageを統合する

Laravelのファイルストレージを利用してCloudStorageを扱えるようにしてみます。Laravelに統合するにあたってゼロからつくるのではなくすでにパッケージが有志の方によって作られているのでこれを利用したいと思います。 導入 READMEに書かれている通りcomposeをつかってインストールします。インストールした後は、.envとfilesystem.phpに必要な情報を追加してください。 エラーを回避する バケットのアクセスコントロールが「均一」になっているとlaravel-google-cloud-storageを使ってオブジェクトをアップロードすると失敗します。 Cannot insert legacy ACL for an object when uniform bucket-level access is enabled おそらく原因はgithubのissueのコメントに書かれていることなのではないかと思います。 https://github.com/Superbalist/laravel-google-cloud-storage/issues/80#issuecomment-616557477 なので、このままではバケットのアクセスコントロールが「均一」になっているとこのファイルシステムでのアプロード機能が使えなくなるので、少し手を加えます。 ServiceProviderを作成する エラーが起きる原因は、laravel-google-cloud-storageがアダプターとしてflysystem-google-cloud-storageを利用していることにあります。エラーを回避する方法がプルリクエストで提案されています。要は、GoogleStorageAdapterクラスのgetOptionsFromConfigメソッドをいじりたいので、GoogleStorageAdapterクラスを拡張したクラスを作成して、getOptionsFromConfigメソッドをオーバーライドしてアクセスコントロールが「均一」のバケットにも対応できるように処理を修正して、このクラス自身を返すというものです。これをLaravelのカスタムファイルシステムで実現させるために、独自のサービスクラスを作ります。作成したサービスプロバイダーの中身は下記になります。 app/providers/GoogleCloudStorageServiceProvider.php <?php namespace App\Providers; use Google\Cloud\Storage\StorageClient; use Illuminate\Support\Arr; use Superbalist\LaravelGoogleCloudStorage\GoogleCloudStorageServiceProvider as GCSProvider; use Superbalist\Flysystem\GoogleStorage\GoogleStorageAdapter; class GoogleCloudStorageServiceProvider extends GCSProvider { /** * Create a new StorageClient * * @param mixed $config * @return \Google\Cloud\Storage\StorageClient */ private function createClient($config) { $keyFile = Arr::get($config, 'key_file'); if (is_string($keyFile)) { return new StorageClient([ 'projectId' => $config['project_id'], 'keyFilePath' => $keyFile, ]); } if (! is_array($keyFile)) { $keyFile = []; } return new StorageClient([ 'projectId' => $config['project_id'], 'keyFile' => array_merge(["project_id" => $config['project_id']], $keyFile) ]); } public function boot() { $factory = $this->app->make('filesystem'); /* @var FilesystemManager $factory */ $factory->extend('gcs', function ($app, $config) { $storageClient = $this->createClient($config); $bucket = $storageClient->bucket($config['bucket']); $pathPrefix = Arr::get($config, 'path_prefix'); $storageApiUri = Arr::get($config, 'storage_api_uri'); $adapter = $this->resolveAdapter($storageClient, $bucket, $pathPrefix, $storageApiUri); return $this->createFilesystem($adapter, $config); }); } public function resolveAdapter($storageClient, $bucket, $pathPrefix = null, $storageApiUri = null) { return new class ($storageClient, $bucket, $pathPrefix, $storageApiUri) extends GoogleStorageAdapter { protected function getOptionsFromConfig(\League\Flysystem\Config $config) { $options = []; if (empty($this->bucket->info()['iamConfiguration']['uniformBucketLevelAccess']['enabled'])) { if ($visibility = $config->get('visibility')) { $options['predefinedAcl'] = $this->getPredefinedAclForVisibility($visibility); } else { $options['predefinedAcl'] = $this->getPredefinedAclForVisibility(AdapterInterface::VISIBILITY_PRIVATE); } } if ($metadata = $config->get('metadata')) { $options['metadata'] = $metadata; } return $options; } }; } } createFilesystemに渡す$adapterに、GoogleStorageAdapterを拡張したクラスを渡しています。またこのサービスクラスもlaravel-google-cloud-storageのGoogleCloudStorageServiceProviderを拡張しています。 作成したサービスプロバイダーをapp.phpに登録します。 config/app.php ... 'providers' => [ ... App\Providers\GoogleCloudStorageServiceProvider::class, ], ... 必要な作業は終わりました。これでアクセスコントロールが「均一」のバケットに対してもオブジェクトがアップロードできるようになります。 public function upload(Request $request) { $file = $request->file('test'); $disk = Storage::disk('gcs'); $disk->put('test.txt', file_get_contents($file)); } Laravelでカスタムファイルシステムを作成する方法については、下記の記事で解説しているのでぜひ参考にしてみてください。
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

cookieを使って、見せるページを分岐させる。

自分のための忘備録です。 そのページに初回の人と2回目以降の人を分けて見せたいとかの時にクッキーでできるみたいです。 クッキーは簡単に設置できるみたいです。 有効期限が一時間のクッキー設置 session_start()はいらないかもです。。 htmlにphpで記入 <?php session_start(); ?> <?php $value = 1; if(!isset($_COOKIE['visited'])) { setcookie("visited", $value, time()+3600); ?> //ここに初回の人に見せる内容 <?php exit; } ?> //ここに2回目以降の人に見せる内容 問題点 ブラウザでクッキー無効にしていたら効かないみたいです。 クッキーの代わりにセッションというのがあるみたいです。 クッキーとセッションの違い クッキー・・・ブラウザに情報を残す セッション・・・サーバーに情報を残す セッションの有効期限を変更するには php.iniの「session.cookie_lifetime」を変更する必要があるみたいですが、 レンタルサーバー等では変更できるかどうかは確認しないとわからないです。 他にもphpの関数で設定できるみたいですが、これもレンタルサーバーでは効かないこともあるみたいです。 セッションで有効期限1時間で設置 <?php // セッションの有効期限を設定 session_set_cookie_params(3600); // セッション管理開始 session_start(); if (!isset($_SESSION['visited'])) { $_SESSION['visited'] = 1; ?> //ここに初回の人に見せる内容 <?php exit; } ?> //ここに2回目以降の人に見せる内容 セッションの削除 テストとかするとき必要でした。 php unset($_SESSION['visited']); 参考しました。 https://www.sejuku.net/blog/25276
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Wordpressで投稿画像のファイル名を英語にリネームする。

自分のための忘備録です。 (・ω・)< kubiee君、以前作ったwordpressの画像のファイル名が日本語になってるよ ・・・(やばい・何か問題があるのかな・・?) >(´∇`) 問題点 今後wordpressを引っ越すときにエラーが出るみたいです。 こちらのサイトを参考に過去の投稿画像をリネームしました。 今後の投稿画像も自動で英語にリネームする functions.phpに以下を追加 functions.php function rename_file_md5($fileName) { $i = strrpos($fileName, '.'); if ($i) $Exts = '.'.substr($fileName, $i + 1); else $Exts = ''; $fileName = md5(time().$fileName).$Exts; return strtolower($fileName); } add_filter('sanitize_file_name', 'rename_file_md5', 10);
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

スパム対策:google reCAPTCHAの設置

自分のための忘備録です。 reCAPTCHAとは google reCAPTCHAとはフォーム送信の際に画像認証などを用い、botを防ぐ仕組み。 V2とV3がある。 v2とv3の違い V2・・・画像認証が出てチェックさせる。フォーム送信に手間がかかる。 V3・・・フォームでの挙動から自動でbotか判断する。フォーム送信に手間がかからないが、効いてるのかいまいち分からない。 設置方法 ①まずgoogleアカウントを作り、ダッシュボードでプロジェクトを作っておく 上の「Google Cloud Platform」の横にあるところから「新しいプロジェクト」 ②reCAPTCHAを設置したいドメインを登録して、v2かv3を選んでキーをもらう サイトキーとシークレットキーがある。 v2の設置コード htmlだけで済ませたいならこちら htmlとphpで処理を分けるならこちら v3の設置コード v3設置してて問題点が出てきた どうやらreCAPTCHAはトークンを取得して5分経つとタイムアウトエラー出るみたいです。 タイムアウトエラー対策 タイムアウトエラーだけ無視できるようにちょっと変更します。 ついでに条件を「スコアが0.9以上なら成功」に変更 フォームのphp if (!empty($_POST['recaptchaResponse'])) { $secret = 'シークレットキーを入れる'; $verifyResponse = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secret.'&response='.$_POST['recaptchaResponse']); $reCAPTCHA = json_decode($verifyResponse); $reCAPTCHA_error = []; if($reCAPTCHA->{'error-codes'}) { $reCAPTCHA_error = $reCAPTCHA->{'error-codes'}; }; if ($reCAPTCHA->score >= 0.9 || (count($reCAPTCHA_error) === 1 && $reCAPTCHA_error[0] === 'timeout-or-duplicate')) { // たぶん人間なので送信とかの処理 } else { // ボットかも } } ただこれだとタイムアウトエラーが出ていたらscore関係なくtrueになってしまいます。 recaptureはタイムアウトエラーになるとscoreが消えてしまうので仕方ないみたいです。 効いてるか確認 参考させていただきました https://norando.net/recaptcha-v3_timeout-or-duplicate/ https://blog.4breaker.com/2020/02/29/post-358/
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel MIMEのimage/jpegの配列が変化しているので注意する

目的 Laravelの内部ファイルの仕様が一部変更になっていたので注意喚起のための自分メモとして残す 詳細 アプリ名ディレクトリ/vendor/symfony/mime/MimeTypes.phpの'image/jpeg' => ['jpeg', 'jpg', 'jpe'],が'image/jpeg' => ['jpg', 'jpeg', 'jpe'],に変更になった。 コミットへのリンク https://github.com/symfony/symfony/pull/38407/files
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む

Laravel8でのプロジェクト開始について(自分用メモ)

概要 2021年3月末からLaravelを触ってみた、ほんとに初心者です。 LaravelはおろかPHPすら、なんかみたことあるなぁくらい。 簡単なwebサイトをちょろっと作れるくらいになりたいなぁと。 作業に当たってプロジェクトをする作れるように手順をメモしてます。 (結構、プロジェクトの根底からの実装を修正したいことが、あるはず・・・なので) 絶賛、実装含めて触っているところなので、しばらくは更新するかもしれない。 自分用のメモをまとめていたのですが、 もっとこうしたほうがいいよとか、こんなの便利だよとかあったら教えてもらいたい というのもあり+ちゃんと整理したかったので公開してみます。 【環境】 PHP 8.0.0 Laravel Framework 8.36.2 windows 10 node v14.16.0 では、ここから手順です。 インストールは割愛します。 1.プロジェクト作成 cmd cd C:\Users\ADMIN\source\repos composer create-project laravel/laravel --prefer-dist TEST 2.composerにてインストール(任意) データベースからLaravelのSeederを逆生成したい場合 cmd cd TEST composer require --dev "orangehill/iseed" 3.app/Providers/RouteServiceProvider.phpを修正 設定系 (Laravel8から変わってるらしい。) ※実際は、ファイルコピーしてます。 before // protected $namespace = 'App\\Http\\Controllers'; after protected $namespace = 'App\\Http\\Controllers'; 4.config/app.phpを修正 設定系 ※実際は、ファイルコピーしてます。 before 'timezone' => 'UTC', 'locale' => 'en', 'faker_locale' => 'en_US', after 'timezone' => 'Asia/Tokyo', 'locale' => 'ja', 'faker_locale' => 'ja_JP', 'providers' => [ ・・・ Orangehill\Iseed\IseedServiceProvider::class, //追加 5.一回動作確認 cmd php -S localhost:8000 -t public http://localhost:8000/ へアクセス。 ~ここからは自分の実装用~ 6.model作成 aオプションで全部作る a = all : model・factroy・seeder・controller(resorce) cmd php artisan make:model Employee -a 各モデルに、ソフトデリート(論理削除)使用に変更 Employee.php <?php namespace App\Models; use Illuminate\Database\Eloquent\Factories\HasFactory; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; //追加 class Employee extends Model { use HasFactory; use SoftDeletes; //追加 } 7.migrateファイル修正 ご自由に。 ※自分メモ C:\Users\ADMIN\source\repos\TEST\database\migrations の整理 C:\Users\ADMIN\source\projecct作成時model作成後\database\migrations をコピー DB migrations を整理 8.マイグレーション実行 cmd php artisan migrate:refresh --seed 参考 //migrateのみ php artisan migrate:refresh //seedのみ php artisan db:seed 9.サーバ起動 cmd php -S localhost:8000 -t public http://localhost:8000/ へアクセス。 その他 メモ 現在のテーブルからseedファイル作成(DatabaseSeeder.phpにも更新) php artisan iseed tableName 画面作成時手順 ①DB設定 ②コントローラ作成(メソッド作成)  php artisan make:controller controllerName ③view編集(画面作成) ④ルーティング設定 -- バージョン確認 php artisan --version
  • このエントリーをはてなブックマークに追加
  • Qiitaで続きを読む