Advanced-usage.md.txt 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. # Advanced usage
  2. ## Configuration via `QROptions`
  3. The [`QROptions`](https://github.com/chillerlan/php-qrcode/blob/main/src/QROptions.php) class is a container based on [chillerlan/php-settings-container](https://github.com/chillerlan/php-settings-container) that behaves similar to a [`\stdClass`](https://www.php.net/manual/class.stdclass) object, but with fixed properties.
  4. A list with all available `QROptions` can be found under [configuration settings](../Usage/Configuration-settings.md).
  5. ```php
  6. $options = new QROptions;
  7. // set some values
  8. $options->version = 7; // property "version" exists
  9. $options->foo = 'bar'; // property "foo" does not exist (and will not be created)
  10. // retrieve values
  11. var_dump($options->version); // -> 7
  12. var_dump($options->foo); // -> null (no error will be thrown)
  13. ```
  14. ### Supply an `iterable` of options
  15. The constructor takes an `iterable` of `$key => $value` pairs. For each setting an optional setter will be called if present.
  16. ```php
  17. $myOptions = [
  18. 'version' => 5,
  19. 'outputType' => QROutputInterface::GDIMAGE_PNG,
  20. 'eccLevel' => EccLevel::M,
  21. ];
  22. $options = new QROptions($myOptions);
  23. ```
  24. You can also set an `iterable` of options on an existing QROptions instance:
  25. ```php
  26. $options->fromIterable($myOptions);
  27. ```
  28. ### Load and save JSON
  29. The settings can be saved to and loaded from JSON, e.g. to store them in a database:
  30. ```php
  31. $json = $options->toJSON(JSON_THROW_ON_ERROR);
  32. // via JsonSerializable interface
  33. $json = json_encode($options, JSON_THROW_ON_ERROR);
  34. // via __toString()
  35. $json = (string)$options;
  36. $options = (new QROptions)->fromJSON($json);
  37. // on an existing instance - properties will be overwriten
  38. $options->fromJSON($json);
  39. ```
  40. ### Extending the `QROptions` class
  41. In case you need additional settings for your output module, just extend `QROptions`...
  42. ```php
  43. class MyCustomOptions extends QROptions{
  44. protected string $myParam = 'defaultValue';
  45. // ...
  46. }
  47. ```
  48. ...or use the [`SettingsContainerInterface`](https://github.com/chillerlan/php-settings-container/blob/main/src/SettingsContainerInterface.php), which is the more flexible approach.
  49. ```php
  50. trait MyCustomOptionsTrait{
  51. protected string $myParam = 'defaultValue';
  52. // ...
  53. // an optional magic setter, named "set_" + property name
  54. protected function set_myParam(string $myParam):void{
  55. $this->myParam = trim($myParam);
  56. }
  57. // an optional magic getter, named "get_" + property name
  58. protected function get_myParam():string{
  59. return strtoupper($this->myParam);
  60. }
  61. }
  62. class MyCustomOptions extends SettingsContainerAbstract{
  63. use QROptionsTrait, MyCustomOptionsTrait;
  64. }
  65. // set the options
  66. $myCustomOptions = new MyCustomOptions;
  67. $myCustomOptions->myParam = 'whatever value';
  68. ```
  69. Extend the `SettingsContainerInterface` on-the-fly:
  70. ```php
  71. $myOptions = [
  72. 'myParam' => 'whatever value',
  73. // ...
  74. ];
  75. $myCustomOptions = new class($myOptions) extends SettingsContainerAbstract{
  76. use QROptionsTrait, MyCustomOptionsTrait;
  77. };
  78. ```
  79. ## `QRCode` methods
  80. Aside of invoking a `QRCode` instance with an optional `QROptions` object as parameter, you can also set the options instance after invocation.
  81. After invocation of the `QROptions` instance, values can be set without calling `QRCode::setOptions()` again (instance is backreferenced), however, this may create side effects.
  82. ```php
  83. // instance will be invoked with default settings
  84. $qrcode = new QRCode;
  85. // set options after QRCode invocation
  86. $options = new QROptions;
  87. $qrcode->setOptions($options);
  88. ```
  89. ### Save to file
  90. You can specify an output file path in which the QR Code content is stored (this will override the `QROptions::$cachefile`
  91. setting, see [common output options](../Customizing/Common.md#save-to-file)):
  92. ```php
  93. $qrcode->render($data, '/path/to/qrcode.svg');
  94. printf('<img src="%s" alt="QR Code" />', '/path/to/qrcode.svg');
  95. ```
  96. ### Render a `QRMatrix` instance
  97. You can render a [`QRMatrix`](https://github.com/chillerlan/php-qrcode/blob/main/src/Data/QRMatrix.php) instance directly:
  98. ```php
  99. // a matrix from the current data segments
  100. $matrix = $qrcode->getQRMatrix();
  101. // from the QR Code reader
  102. $matrix = $readerResult->getQRMatrix();
  103. // manually invoked
  104. $matrix = (new QRMatrix(new Version(7), new EccLevel(EccLevel::M)))->initFunctionalPatterns();
  105. $output = $qrcode->renderMatrix($matrix);
  106. // save to file
  107. $qrcode->renderMatrix($matrix, '/path/to/qrcode.svg');
  108. ```
  109. ### Mixed mode
  110. Mixed mode QR Codes can be generated by adding several data segments:
  111. ```php
  112. // make sure to set a proper internal encoding character set
  113. // ideally, this should be set in php.ini internal_encoding,
  114. // default_charset or mbstring.internal_encoding
  115. mb_internal_encoding('UTF-8');
  116. // clear any existing data segments
  117. $qrcode->clearSegments();
  118. $qrcode
  119. ->addNumericSegment($numericData)
  120. ->addAlphaNumSegment($alphaNumData)
  121. ->addKanjiSegment($kanjiData)
  122. ->addHanziSegment($hanziData)
  123. ->addByteSegment($binaryData)
  124. ->addEciSegment(ECICharset::GB18030, $encodedEciData)
  125. ;
  126. $output = $qrcode->render();
  127. // render to file
  128. $qrcode->render(null, '/path/to/qrcode.svg');
  129. ```
  130. The [`QRDataModeInterface`](https://github.com/chillerlan/php-qrcode/blob/main/src/Data/QRDataModeInterface.php) offers the `validateString()` method (implemended for `AlphaNum`, `Byte`, `Hanzi`, `Kanji` and `Number`).
  131. This method is used internally when a data mode is invoked, but it can come in handy if you need to check input data beforehand.
  132. ```php
  133. if(!Hanzi::validateString($data)){
  134. throw new Exception('invalid GB2312 data');
  135. }
  136. $qrcode->addHanziSegment($data);
  137. ```
  138. ### QR Code reader
  139. In some cases it might be necessary to increase the contrast of a QR Code image:
  140. ```php
  141. $options->readerUseImagickIfAvailable = true;
  142. $options->readerIncreaseContrast = true;
  143. $options->readerGrayscale = true;
  144. $result = (new QRCode($options))->readFromFile('path/to/qrcode.png');
  145. ```
  146. The `QRMatrix` object from the [`DecoderResult`](https://github.com/chillerlan/php-qrcode/blob/main/src/Decoder/DecoderResult.php) can be reused:
  147. ```php
  148. $matrix = $result->getQRMatrix();
  149. // ...matrix modification...
  150. $output = (new QRCode($options))->renderMatrix($matrix);
  151. // ...output
  152. ```