webiik/staticpage

StaticPage 允许您生成静态页面。

1.1 2020-01-27 16:19 UTC

This package is auto-updated.

Last update: 2024-09-28 03:10:03 UTC


README

StaticPage

StaticPage 允许您从几乎任何 PHP 应用程序动态生成静态内容。它旨在在任何路由控制器中使用,并使用 NGiNX 或其他 Web 服务器提供静态文件。

安装

composer require webiik/staticpage

步骤

要使 StaticPage 运作,请按照以下两个步骤操作

  1. 更新您的路由控制器

    假设您有一个 run() 方法,您将其用作路由控制器。

    public function run(): void
    {
        // Page URI
        $uri = '/foo/bar/';
        
        // Page template
        $page = '<h1>Meow World!</h1>';
    
        // Save static file the web server will try to serve with every next request  
        $staticPage = new Webiik\StaticPage\StaticPage();
        $staticPage->save($page, $uri);
    
        // Show dynamic page when the server didn't serve the static page  
        echo $page;
    }
  2. 更新您的 Web 服务器配置(NGiNX 示例)

  • /_site${uri} /_site${uri}index.html 添加到主 location 中的 try_files 指令的开头。它告诉 NGiNX 首先尝试提供静态文件。例如
    location / {
        try_files /_site${uri} /_site${uri}index.html $uri $uri/ /index.php?$query_string;
    }
  • 检查配置并重新启动服务器。

配置

setDir

setDir(string $dir): void

setDir() 设置所有生成的静态文件存储的相对路径。默认路径为 ./_site

$staticPage->setDir('./_site');

生成

save

save(string $data, string $uri, string $file = 'index.html'): void

save() 根据指定的 $uri 创建目录结构,并在其中保存包含 $data 内容的 $file

$staticPage->save('<h1>Meow World!</h1>', '/foo/bar/');

删除

delete

⚠️ 使用此方法时请务必小心。

delete(bool $test = true): void

delete() 删除 $dir 的内容。当 $test 模式设置为 true 时,它只打印要删除的文件但不删除它们。

$staticPage->delete();

此方法可以从 CLI 调用。它接受两个参数 $dir$test

php StaticPage.php /absolute/path/to/static/_site true

资源