Jump to content
Sign in to follow this  
墨香年少

symfony6 using service

Recommended Posts

// src/Service/PaymentLogService.php

namespace App\Service;

class PaymentLogService
{
    private $logDirectory;

    public function __construct(string $logDirectory)
    {
        $this->logDirectory = $logDirectory;
    }

    public function appendToPaymentLog($pno, $content): void
    {
        $filePath = $this->logDirectory . '/' . $pno;

        // 确保目录存在
        if (!file_exists(dirname($filePath))) {
            mkdir(dirname($filePath), 0777, true);
        }

        // 追加内容到文件,如果文件不存在则创建
        file_put_contents($filePath, $content, FILE_APPEND);
    }
}
# config/services.yaml
services:
    App\Service\PaymentLogService:
        arguments:
            $logDirectory: '%kernel.project_dir%/log'
// src/Controller/SomeController.php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Response;
use App\Service\PaymentLogService;

class SomeController
{
    private $paymentLogService;

    public function __construct(PaymentLogService $paymentLogService)
    {
        $this->paymentLogService = $paymentLogService;
    }

    public function appendLogAction($pno): Response
    {
        $content = date('Y-m-d H:i:s') . "\n";
        $this->paymentLogService->appendToPaymentLog($pno, $content);

        return new Response('Log updated.');
    }
}

 


目之所及,皆是回忆,心之所想,皆是过往

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

×
×
  • Create New...

Important Information

注册必须使用2-8个中文汉字作为账号