truecastdesign / true
此库为运行 True 框架提供了基础类。
Requires
- php: >=5.5.0
- dev-master
- v2.23.0
- v2.22.7
- v2.22.5
- v2.22.3
- v2.22.2
- v2.22.1
- v2.22.0
- v2.21.6
- v2.21.5
- v2.21.4
- v2.21.3
- v2.21.1
- v2.21.0
- v2.20.3
- v2.20.2
- v2.20.1
- v2.20.0
- v2.19.6
- v2.19.5
- v2.19.4
- v2.19.3
- v2.19.2
- v2.19.0
- v2.18.1
- v2.18.0
- v2.17.4
- v2.17.3
- v2.17.2
- v2.17.1
- v2.17.0
- v2.16.2
- v2.16.1
- v2.16.0
- v2.15.4
- v2.15.3
- v2.15.2
- v2.14.1
- v2.14.0
- v2.13.2
- v2.13.1
- v2.12.0
- v2.11.1
- v2.11.0
- v2.10.7
- v2.10.6
- v2.10.4
- v2.10.3
- v2.10.2
- v2.10.1
- v2.10.0
- v2.9.2
- v2.9.1
- v2.9.0
- v2.8.5
- v2.8.4
- v2.8.3
- v2.8.2
- v2.8.1
- v2.8.0
- v2.7.1
- v2.7.0
- v2.6.2
- v2.5.9
- v2.5.8
- v2.5.0
- v2.4.1
- v2.4.0
- v2.3.0
- v2.2.3
- v2.2.2
- v2.2.1
- v2.1.2
- v2.1.1
- v2.1.0
- v2.0.2
- v2.0.1
- v2.0.0
- v1.28.0
- v1.27.0
- v1.26.5
- v1.25.4
- v1.25.2
- v1.25.1
- v1.25.0
- v1.24.4
- v1.24.3
- v1.24.1
- v1.24.0
- v1.23.2
- v1.23.1
- v1.22.0
- v1.21.1
- v1.21.0
- v1.20.0
- v1.19.1
- v1.17.0
- v1.16.0
- v1.15.1
- v1.15.0
- v1.14.6
- v1.14.5
- v1.14.4
- v1.14.2
- v1.14.1
- v1.14.0
- v1.13.1
- v1.13.0
- v1.11.9
- v1.11.6
- v1.11.5
- v1.11.4
- v1.11.3
- v1.11.2
- v1.11.1
- v1.11.0
- v1.10.10
- v1.10.9
- v1.10.8
- v1.10.7
- v1.10.6
- v1.10.5
- v1.10.4
- v1.10.3
- v1.10.2
- v1.10.1
- v1.10.0
- v1.9.2
- v1.9.1
- v1.9.0
- v1.8.0
- v1.7.10
- v1.7.9
- v1.7.8
- v1.7.7
- v1.7.6
- v1.7.5
- 1.7.4
- v1.7.2
- v1.7.1
- v1.7.0
- v1.6.3
- v1.6.1
- v1.6.0
- v1.5.13
- v1.5.12
- v1.5.11
- v1.5.10
- v1.5.9
- v1.5.8
- v1.5.7
- v1.5.6
- v1.5.5
- v1.5.4
- v1.5.3
- v1.5.2
- v1.5.1
- v1.5.0
- v1.4.5
- v1.4.4
- v1.4.2
- v1.4.0
- v1.3.3
- v1.3.2
- v1.3.1
- v1.3.0
- v1.2.0
- v1.1.15
- v1.1.13
- v1.1.12
- v1.1.11
- v1.1.10
- v1.1.9
- v1.1.8
- v1.1.7
- v1.1.6
- v1.1.5
- v1.1.4
- v1.1.3
- v1.1.2
- v1.1.1
This package is auto-updated.
Last update: 2024-09-23 18:15:44 UTC
README
True - True 框架的基础类
这些类构成了 True 框架的基本功能。
需要 PHP 7.1 或更高版本。
安装
使用 composer 安装
$ composer require truecastdesign/true
Apache 的 .htaccess 文件
AddHandler application/x-httpd-php .html .phtml .php
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule .? - [E=HEADER>Authorization:%{HTTP:Authorization}]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^ index.php [QSA,L]
</IfModule>
目录表
文件设置
/public_html/index.php
<?php require '../init.php';
/init.php
<?php define('BP', __DIR__); require 'vendor/autoload.php'; $App = new True\App; $App->load('site.ini'); if ($App->config->site->debug) { $GLOBALS['debug'] = true; error_reporting(E_ALL & ~E_NOTICE); } else { $GLOBALS['debug'] = false; error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING); } $App->request = new True\Request; $App->response = new True\Response; $App->router = new True\Router($App->request); $App->view = new True\PhpView; # global css and js files $App->view->css = '/vendor/truecastdesign/true/assets/default.css, /assets/css/site.css'; # global css files # You can also add them on separate lines or different places in your code $App->view->css = '/assets/example1.css'; $App->view->css = '/assets/example2.css'; # both will be combined and minified. This works for JS files as well. $App->view->js = '/assets/js/file1.js, /assets/js/file2.js'; # global js files # If you need to pass variables to the layout template or page template globally, you can use the variables key on the PhpView object as an key value array item. $App->view->variables = ['key'=>'value']; $App->view->variables = ['key2'=>'value2']; $App->view->variables = ['key'=>'value', 'key3'=>'value3']; # all the arrays will get merged together so you can keep added them and they will all be available. In the view: <?=$key?> <?=$key2?> <?=$key3?> # check routes require 'app/routes.php'; function e($var) { return htmlspecialchars($var, ENT_QUOTES, 'UTF-8'); } function p($var) { print_r($var); } function ph($var) { echo '<!--'; print_r($var); echo '-->'; }
请求对象
路由器对象创建请求对象的实例,并将其插入任何控制器作为 $request。
路由器还将 $request 对象传递给路由闭包,如下所示。
$App->router->get('/api/user/*:id', function($request){ echo $request->route->id; });
在请求对象中处理上传的图像
检查是否上传了文件
if ($request->files->file->uploaded) { // do something like move or resize it echo $request->files->file->ext; // jpg echo $request->files->file->mime; // image/jpeg echo $request->files->file->tmp_name; // /path/j23k4j8d }
调整图像大小
$request->files->file->imageWidth = 800; $request->files->file->imageHeight = 800; try { $request->files->file->resize(); } catch (Exception $e) { echo $e->getMessage(); }
上述代码中的 'file' 关键字是文件输入字段的名称。请确保不要在名称中使用破折号 (-),因为这会破坏对象引用。只需使用下划线或驼峰命名。如果您设置了一个尺寸,另一个将为您计算。
裁剪图像
裁剪方法允许您从图像的顶部、右侧、底部或左侧裁剪出尺寸。传递给数组的值是顺时针方向的,就像在 CSS 中一样。
try { $request->files->file->crop([0,20,0,0]); } catch (Exception $e) { echo $e->getMessage(); }
自动裁剪正方形图像
try { $request->files->file->cropSquare(); } catch (Exception $e) { echo $e->getMessage(); }
要自动裁剪正方形图像,同时保留顶部部分并自动删除底部,请使用 cropBottomSquare() 方法。
try { $request->files->file->cropBottomSquare(); } catch (Exception $e) { echo $e->getMessage(); }
要自动裁剪正方形图像,同时保留底部部分并自动删除顶部,请使用 cropTopSquare() 方法。
try { $request->files->file->cropTopSquare(); } catch (Exception $e) { echo $e->getMessage(); }
裁剪图像或调整其大小后,您可以使用 move 方法将其移动到新位置,并传递路径和文件名。要使用上传文件的扩展名,请使用 $request->files->file->ext 属性。
try { $request->files->file->move('/path/', 'newFileName.'.$request->files->file->ext); } catch (Exception $e) { echo $e->getMessage(); }
为 REST 或类似响应创建响应
示例
$App->response('{"result":"success"}', 'json', 200, ["Cache-Control: no-cache"]);
解释
$App->response('响应正文', '类型: json, html, xml', 状态码, 原始头信息数组);
您仍然可以 echo 和 print_r 您需要的任何内容,而不会覆盖它。这对于调试非常有用。
在响应方法末尾有一个 die() 调用,因此它需要是您最后想要运行的。这允许在控制器中在错误响应之后跟随成功响应。
try { // run method } catch (Exception $e) { $App->response('{"result":"error", "error":"'.$e->getMessage().'"}', 'json', 401); } $App->response('{"result":"success"}', 'json'); // this will run if the above // response does not but will not run if there was already a response run above.
使用控制器
控制器应该是位于 app/controllers 目录中的 .php 文件。您可以通过自定义路由触发它们运行,例如 $App->get('/path', 'filename.php'); 或者如果您使用的是 TrueFramework 中的默认路由,它会自动处理控制器和视图。在这种情况下,您可以将路径与控制器和视图匹配。如果网址是 www.domain.com,它将运行 index.php 控制器并显示 index.phtml 视图。您可以完全跳过控制器,因为它是通过 @include 运行的,如果文件不存在,它将静默地跳过。
控制器应该是简单的 PHP 脚本,而不是类。每个路由一个 PHP 文件。将控制器嵌套在以父控制器命名的目录中。
示例:路径 -> 控制器 /about -> about.php /about/staff -> about/staff.php /about/staff/john-doe -> about/staff/john-doe.php
以下是默认路由的示例。您可以按需修改它。
$App->any('/*:path', function($request) use ($App) { $vars = []; @include $App->controller($request->route->path); $vars['config'] = $App->config; # check selected nav item $vars['selectedNav'] = (object) [$request->route->path => ' class="sel"']; $App->view->render($request->route->path.'.phtml', $vars); });
控制器会接收到 $App 对象和 $request 对象。
使用 PHPView
在您的 init.php 文件或您想放置的任何位置,创建类的实例。
如果您正在使用 True 框架,最好将其设置为 $App->view,这样您就可以访问它,并且它位于一个可预测的位置。如果您喜欢,也可以不设置。
$App->view = new True\PhpView;
设置 PHPView 变量
设置全局 CSS 文件。使用从 public 根目录的路径和文件名,以逗号分隔的列表。
PHPView 将合并所有 CSS 文件,并对代码进行压缩,以便在模板中的 $_css 变量中输出。
$App->view->css = '/assets/css/site.css';
设置全局 JS 文件。使用从 public 根目录的路径和文件名,以逗号分隔的列表。
PHPView 将合并所有 JS 文件,并对代码进行压缩,以便在模板中的 $_js 变量中输出。如果 JS 文件路径包含 http,例如来自 CDN 或其他来源,则不会将该资源合并到合并和压缩的文件中。它将作为一个单独的资源添加。
$App->view->js = '/assets/js/testing.js, /assets/js/testing2.js';
页面浏览器缓存
设置为 true 或 false。默认情况下启用缓存,并设置为一周后过期。可以通过视图元数据的顶部控制单个页面缓存。在视图元数据中使用 cache=false 关闭仅该页面的缓存。
$App->view->cache = true;
其他变量
$App->view->title = "Title Tag"; $App->view->description = "This is the meta description and og:description"; $App->view->canonical = "http://www.domain.com/canonical-url"; $App->view->linkText = "Clickable Text to link to page"; $App->view->headHtml = "<script src='/path/js/dom/js'></script>"; $App->view->html // page body HTML $App->view->breadcrumbs // array of breadcrumbs with name and url // populate using meta area of view file like the following. Only on pages with parent pages. Home is not a parent page according to Google. Put them in decending order from parents down. // breadcrumb[] = "Top Parent Title|/parent" // breadcrumb[] = "Next Parent Title|/parent/other-parent" $App->view->created = "2022-12-01" // set the date the page was created. It can be outputted or used by calling $App->view->created. If you want a different date format, call $App->view->created("M d, Y") can pass the PHP date formatting string you want. $App->view->modified = "2022-12-01" // You can set the page or article modified date if you want full control of it. This variable will also be auto filled if not provided from the modified date of the view file. Just like the created variable, you can format it by calling $App->view->modified("M d, Y");
在模板中按照以下方式输出这些变量。
<?=$App->view->headHtml?>
输出 CSS 和 JS 到模板
CSS 和 JS 视图变量是特殊的,因为要输出压缩和合并的版本到页面,您使用一个特殊的变量,而不是像其他变量一样使用 $App->view->css。
对于 CSS
<?=$App->view->cssoutput?>
CSS 输出应放在您的 head 标签中。
对于 JavaScript
<?=$App->view->jsoutput?>
JS 输出应放在 body 标签的关闭之前。
CSS 和 JS 文件夹中都需要有缓存文件夹。
PHPView 将将压缩、版本化和合并的文件放在 /assets/css/cache 和 /assets/js/cache 中。确保这些目录存在,以便它能够正常工作。
自定义变量
您现在可以使用自己的自定义变量,这样您就可以将值传递到基本模板,例如在页眉中输出。
在 view/.phtml 文件的 meta 区域中添加您的自定义变量,如下所示:
customVariable = "custom value"
{endmeta}
当您将此放入文件的 meta 区域时,基本模板将能够访问并检查它是否可用,如下所示。
<?if ($App->view->isset('customVariable')):?> <?=$App->view->customVariable?> <?endif?>
创建和使用视图文件
视图文件需要命名为 {name}.phtml
它们位于 /app/views 目录中
与 /name 匹配的 URL 匹配 /app/views/name.phtml 文件。与 /name/othername 匹配的 URL 匹配 /app/views/name/othername.phtml 文件
应该有一个包含所有网站 HTML 标签的基础视图,这些标签围绕着来自页面视图文件的主要内容。它将插入例如 name.phtml 的内容,并将其插入基础视图中的任何位置。
$App->view->render('page.phtml', ['var1'=>6]);
第二个参数是一个变量数组,这些变量将可用于页面。在上面的示例中,$var1 将等于 6。您也可以这种方式传递类对象。
使用自定义布局(header/footer 代码)插入视图
创建一个自定义控制器,并在控制器中放入
$App->view->layout = BP."/app/views/_layouts/landing-page.phtml"; $App->view->render('page.phtml');
渲染不在 /app/views 目录中的文件
$App->view->render(BP.'/vendor/truecastdesign/trueadmin/views/not-authorized.phtml');
渲染错误页面
默认错误页面:404-error.phtml 401-error.phtml 403-error.phtml error.phtml
对于 error.phtml 页面,提供了 $errorCode 和 $errorText 变量来显示错误类型。
$App->view->error(404); // other errors supported: 301, 302, 303, 304, 307, 308, 400, 401, 403, 404, 405
设置自定义错误页面
$App->view->403 = 'not-authorized.phtml';
电子邮件
True 框架内置了 SMTP 电子邮件类,用于通过 SMTP 电子邮件账户发送电子邮件,以提供更好的投递性和功能。
$mail = new \True\Email('domain.com', 587, 'tls', 'login'); // ssl and tls are turned on or off automatacally based on the port provided. $mail->setLogin('user@domain.com', 'password') ->setFrom('user@domain.com', 'name') ->addReplyTo('user@domain.com', 'name') ->addTo('user@domain.com', 'name') ->addCc('user@domain.com', 'name') ->addBcc('user@domain.com', 'name') ->addAttachment(BP.'/path/to/filename.jpg') ->addHeader('header-title', 'header value') ->setCharset('utf-16', 'header value') // default: utf-8; values: utf-16, utf-32, ascii, iso 8859-1 ->setSubject('Test subject') ->setTextMessage('Plain text message') ->setHtmlMessage('<strong>HTML Text Message</strong>') ->setHTMLMessageVariables(['name'=>'John Doe', 'phone'=>'541-555-5555', 'message'=>'Plain text message']) ->addHeader('X-Auto-Response-Suppress', 'All'); if ($mail->send()) { echo 'SMTP Email has been sent' . PHP_EOL; } else { echo 'An error has occurred. Please check the logs below:' . PHP_EOL; pr($mail->getLogs()); }
JWT JavaScript Web Token
$Users = new Users($DB); $LoginAttempts = new True\LoginAttempts($DB); $JWT = new True\JWT; $PasswordGenerator = new True\PasswordGenerator; $taAuthConfig = $App->getConfig('trueadminAuth.ini'); $Auth = new True\AuthenticationJWT($Users, $LoginAttempts, $JWT, $PasswordGenerator, $App, [ 'privateKeyFile'=>BP.'/app/data/key_private_rsa.pem', 'publicKeyFile'=>BP.'/app/data/key_public_rsa.pem', 'encryptionPasswordFile'=>'trueadminAuth.ini', 'pemkeyPassword'=>$taAuthConfig->pemkey_password, 'https'=>$taAuthConfig->https, 'ttl'=>$taAuthConfig->pemkey_password, 'alg'=>$taAuthConfig->alg ]); try { if ($Auth->isLoggedIn()) { # user logged in } } catch (Exception $e) { echo $e->getMessage(); }
LogParser
$logFile = BP."/logs/access.log"; $Parser = new True\LogParser($logFile); foreach ($Parser as $row) { print_r($row); }
SEO/OpenGraph LD+JSON
使用SEO类的方法输出LD+JSON schema.org元数据。
全球网站schema
$schemaInfo = (object)[ "base_url"=>$App->config->site->url, "url"=>$App->request->url->full, "title"=>$App->view->title, "description"=>$App->view->description, "site_logo_url"=>$App->config->site->site_logo_url, "site_logo_width"=>$App->config->site->site_logo_width, "site_logo_height"=>$App->config->site->site_logo_height, "site_logo_caption"=>$App->config->site->site_logo_caption, "datePublished"=>$App->view->datePublished, "dateModified"=>$App->view->dateModified, "social_media"=>$App->config->social_media ]; echo $SEO->schemaGraph($schemaInfo);
特定页面schema
<?=$SEO->jsonLD('article', [ 'datePublished'=>'2024-01-01', 'headline':"The great article" ]);?>
可用schema的完整列表
食谱文章组织网站网页博客帖子面包屑商店家庭和建筑业务产品
查看/vendor/truecastdesign/true/src/schemaTypes中的文件以获取每个数组键和值的单独文档。
Google Tag Manager GA4 Javascript代码生成器
使用以下代码以及类似的代码为不同的事件
$eventData = [ 'orderNumber'=>1254875, 'total'=>'$25.80', 'source'=>'BatteryStuff', 'coupon'=>"ZJUE", 'shipping'=>2.80, 'tax'=>0.50, 'items'=>[ [ 'partNumber'=>'rx8', 'name'=>'Battery Charger RX8', 'coupon'=>'ZJUE', 'discount'=>0.30, 'brand'=>"Chargers Unlimited", 'category'=>'Battery Chargers > 12 Volt > Single Bank > 5-10 Amps', 'variant'=>'With Cables', 'price'=>'$7.80', 'quantity'=>'1' ], [ 'partNumber'=>'rx9', 'name'=>'Battery Charger RX9', 'coupon'=>'JEN', 'brand'=>"Chargers Unlimited", 'category'=>'Battery Chargers > 12 Volt > Single Bank > 10-20 Amps', 'price'=>7.90, 'quantity'=>2 ] ] ]; $GoogleTagManager = new True\GoogleTagManager; echo $GoogleTagManager->event('purchase', $eventData);
这将为您输出以下JS代码,包括脚本标签。该类进行基本值验证和过滤。它自动添加货币为USD。如果您需要其他货币,只需使用“currency”键传递即可。
当前事件支持
view_item add_to_cart view_cart begin_checkout login purchase
<script> gtag("event", "purchase", { "currency": "USD", "value": 25.8, "transaction_id": 1254875, "affiliation": "BatteryStuff", "coupon": "ZJUE", "shipping": 2.8, "tax": 0.5, "items": [ { "index": 0, "item_name": "Battery Charger RX8", "item_id": "rx8", "coupon": "ZJUE", "discount": 0.3, "item_brand": "Chargers Unlimited", "item_variant": "With Cables", "price": 7.8, "quantity": 1, "item_category": "Battery Chargers", "item_category2": "12 Volt", "item_category3": "Single Bank", "item_category4": "5-10 Amps" }, { "index": 1, "item_name": "Battery Charger RX9", "item_id": "rx9", "coupon": "JEN", "item_brand": "Chargers Unlimited", "price": 7.9, "quantity": 2, "item_category": "Battery Chargers", "item_category2": "12 Volt", "item_category3": "Single Bank", "item_category4": "10-20 Amps" } ] }); </script>
测试PHPUNIT
测试位于tests文件夹中。
测试列表以及如何运行它们。
% phpunit tests/NonceTest.php
用法
使用可用的文件夹结构在app文件夹中构建您的网站。
app文件夹应位于public文件夹旁边。资产,如图像、CSS、JS、PDF等,应位于public文件夹内的assets文件夹中。
问题
在本地运行时,使用Chrome登录管理区域不会设置cookie。它们需要一个域名。请使用Firefox或Safari进行开发。
