2021年4月3日土曜日

PHP:Symfony-04

1.DIコンテナ

Symfony 4 のDI機能については config ディレクトリ内の services.yaml で定義されている

parameters:

services:
    # default configuration for services in *this* file
    _defaults:
        autowiretrue      # Automatically injects dependencies in your services.
        autoconfiguretrue # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource'../src/'
        exclude:
            - '../src/DependencyInjection/'
            - '../src/Entity/'
            - '../src/Kernel.php'
            - '../src/Tests/'

    # controllers are imported separately to make sure services can be injected
    # as action arguments even if you don't extend any base controller class
    App\Controller\:
        resource'../src/Controller/'
        tags: ['controller.service_arguments']

    # add more service definitions when explicit configuration is needed
    # please note that last definitions always *replace* previous ones

2.実際の例 

名前空間: App\Service

ファイル: src/Service/SampleService.php

<?php

namespace App\Service;
 
class SampleService
{
    public function helloWorld(): string
    {
        return 'hello world.';
    }
 
}


コントローラ上のルーティングから利用

    /**
     * @Route("/service/useService1", methods={"GET"})
     */
    public function useSerivce1(\App\Service\SampleService $sampleService)
    {
        $result = $sampleService->helloWorld();
        
        return $this->render('/service/use_service.html.twig', [
            'body' => $result
        ]);
    }


/serivce/use_service.html.twig

<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <title>{{ title|default('default title')}}</title>
    </head>
    <body>
        {{ body }}
    </body>
</html>


コンストラクタでのインジェクションを試してみます。クラス内で恒常的に使うのに良いです。

    // 利用するサービスクラスをコンストラクタインジェクションする
    private $sampleService;
    
    public function __construct(\App\Service\SampleService $sampleService)
    {
        $this->sampleService = $sampleService;
    }
    
    /**
     * @Route("/service/useService2", methods={"GET"})
     */
    public function useSerivce2()
    {
        $result = $this->sampleService->helloWorld();
        
        return $this->render('/service/use_service.html.twig', [
            'body' => $result
        ]);
    }


設定値の注入

<?php
namespace App\Service;
 
class MailService
{
    private $from_address;
 
    public function __construct($from_address)
    {
        $this->from_address = $from_address;
    }
}


parameters:
    from_address'xxx@yyy.zzz'

services:
    # default configuration for services in *this* file
    _defaults:
        autowiretrue      # Automatically injects dependencies in your services.
        autoconfiguretrue # Automatically registers your services as commands, event subscribers, etc.

    # makes classes in src/ available to be used as services
    # this creates a service per class whose id is the fully-qualified class name
    App\:
        resource'../src/'
        exclude:
            - '../src/DependencyInjection/'
            - '../src/Entity/'
            - '../src/Kernel.php'
            - '../src/Tests/'

    App\Service\MailService:
        arguments:
            $from_address'%from_address%'



コンテナから直接取得する

コンテナに登録済みのオブジェクトは直接取得する事も出来ます。依存性は高くなりますがそうしたい場合もあるかと思いますので記載しておきます。

$sampleService = $this->container->get('App\Service\SampleService');

$from_address = $this->getParameter('from_address');

なお、上記の $this->container->get() で取りに行く方法はコントローラ内では制限が有り利用できない。


2021年4月2日金曜日

PHP:Symfony-03

1.ルーティング

class RootController extends AbstractController

{

    /**

     * @Route("/root", name="root")

     */

    public function index()

    {

        return $this->render('root/index.html.twig', [

            'controller_name' => 'BlogController',

        ]);

    }

}

PHPDocに記載の有る @Route 定義がアノテーションによるルーティングです。”/root”にマッチするURLが来た場合にこの index 関数が実行されます。nameはユニークである必要が有る。

結果はResponseオブジェクト( Symfony\Bundle\FrameworkBundle\Controller\Response)をreturnで返します。$this->render() を呼び出すとTwigでレンダリングした結果をResponseオブジェクトとして返す。

    /**
     * ルーティングを増やす
     * http://127.0.0.1:8000/root/demo/ 
     * @Route("/root/demo", name="root_demo")
     */
    public function demoAction()
    {
        return $this->render('root/index.html.twig', [
            'controller_name' => 'RootController::demo',
        ]);
    }

    /**
     * 引数のあるルーティング
     * http://127.0.0.1:8000/books/detail/20/ 
     * @Route("/books/detail/{book_id}/", name="book_detail", 
     * requirements={"book_id"="\d+"})
     */
    public function bookDetailAction($book_id)
    {
        return $this->render('books/detail.html.twig', [
            'book_id' => $book_id,
            'book_detail' => 'dumy text'
        ]);
    }

    /**
     * リクエスト内容を受け取る
     * http://127.0.0.1:8000/books/detail/?book_id=33
     * @Route("/books/detail/", name="book_detail_for_query")
     */
    public function bookDetailActionForQuery(Request $req)
    {
        $book_id = $req->query->get('book_id');
    
        return $this->render('books/detail.html.twig', [
            'book_id' => $book_id,
            'book_detail' => 'dumy text'
          ]);
    }

    /**
     * HTTPメソッドに応じてルーティングする
     * http://127.0.0.1:8000/books/edit/
     * @Route("/books/edit/", name="book_edit_exec", methods={"POST"})
     */
    public function bookEditExecAction(Request $req)
    {
        return $this->render('books/detail.html.twig', [
            'book_id' => 0,
            'book_detail' => '編集に成功しました'
        ]);
    }

    /**
     * @Route("/demo404")
     */
    public function demo404Action()
    {
        throw $this->createNotFoundException('見つからないようです');
    }


    /**
     * JSONデータを返す
     * http://127.0.0.1:8000/demoJsonResponse
     * @Route("/demoJsonResponse")
     */
    public function demoJsonResponse()
    {
        return $this->json([
            'データ1' => 100,
            'データ2' => 200
        ]);
    }

※ルーテイングがわかりやすい


PHP:Symfony-02

処理方法では5.Xと4.Xで一部違いがあるので
4.Xでの処理を追加する

1.composerでの追加

Serverなどを利用するためにcomposerで追加をする

プロジェクトフォルダ>composer require server

プロジェクトフォルダ>php bin/console server:run 

 [OK] Server listening on http://127.0.0.1:8000                                                       // Quit the server with CONTROL-C.

2.プロジェクトの作成 

omposer create-project symfony/skeleton <プロジェクト名> "4.4.*"

3.コントローラの作成

プロジェクトフォルダ>php bin/console make:controller BlogController


※symfonyコマンドは利用できないようだ


2021年4月1日木曜日

メタボ対策:2021年3月31日号

体重1か月平均(1月) 74.1Kg (目標 74㎏)

体重1か月平均(2月) 73.8kg (目標 74㎏)

体重1か月平均(3月) 71.6Kg (目標 73.5Kg)


メタボ対策は自粛前の昨年とほぼ同じになり、ここでいったん終了
本来4年に及ぶ体重のコントロール
当初は88kg、腹囲は98センチ、今では、すっきりしている
腹囲は現在、81センチ

体調不良などもあり、体重をコントロールをするのが大変な時期もあったが見事に成功

難しいのはおなか一杯に食べてしまう自分自身の弱さ、ついつい食べすぎてしまう
人間ストレスがたまると、よく食べる・・・
これにより、胃腸がおかしくなり、便秘気味の体質がさらに悪くなっていた

1日三食の場合、夜は軽めで、朝昼に重点を置きます、
といって食べすぎは禁物
おやつは10時ごろと15時に甘いものを食べる。
シュークリーム1個や、小さなようかん、チョコレートなら2粒

後は適度の運動、2~3階ならばエスカレータやエレベータを利用せず階段を利用
簡単なことですが、足腰をよく動かすことが必要です
歩くときは早歩きで30分以上、足腰が悪い人を除き、早歩きが原則です
走ると、身体に負担がかかりすぎて空腹感から食べてしまうことが多いので禁物
そのため適度な運動です

後は1週間1回は断食しましょう
難しいことでは、休日の前日の21時から17時まで
胃腸がきれいになり、良い効果を生みます

あくまでも個人的なものであり、人それぞれ、自分に合った方法を見つけるのがベストです

とうさんきがん

下記の企業は悪の根源
ゴキブリ未満の企業であり、下衆社員が多い
とうさんをおいのりいたします
また社員が不幸になることをお祈り申し上げます 

  • DNP
  • 富士ソフト
  • ZOZO