Jump to content
horst

Does using dedicated module files help a lazy programmer?

Recommended Posts

Does using dedicated module files help a lazy programmer?

For a private helper module I wanted to built, I decided to use the possibilities of dedicated files (implemented in PW 2.5.5) and not to write all into a single module file. Until now, I totally missed or forgot about this possibility. To my excuse: on introduction I may have thought not to use it early in my modules to keep backward compatibility. And then totally forgot about it. :)

I allready use a tool for postprocessing in my sites. And I'm not familiar with all those popular node/grunt/gulp/npm/bower/and-what-else stuff out there. It looks to me a bit oversized for small to medium websites. But I also wanted not miss a comfortable, easy to use config for less and sass files, especially for those from frameworks like Bootstrap 3 / 4 or UIKit. So, what my toolbox should get added was a preprocessor (compiler) for sass (.scss) files first. I choosed the UIKit for the first shot.

The created files for a configurable module called PreAndPostProcessor and a process module called ProcessPreProcessor were:

  • PreAndPostProcessor.module
  • PreAndPostProcessor.info.json
  • PreAndPostProcessorConfig.php
     
  • ProcessPreProcessor.module
  • ProcessPreProcessor.info.json
  • ProcessPreProcessor.css
  • ProcessPreProcessor.js

As you can read about the differences to the old-schooled style in Ryans blog post, I focus on what I found out to be most useful for me. Starting with the Config file, I decided to use the $this->add() method in the __constructor(). It is the way what needs less code to define your inputfields for a configpage: just a collection of arrays with field or fieldset definitions.

Mandatory definitions are: type, name, label. Others are optional: description, notes, required, columnWidth, collapsed, showIf, ...
And, of course, you need the definitions specific to your fieldtypes (value, options, ...).

To group some fields into a fieldset, add a key called "children" to the fieldset array and add all field definitions to it as collection. Simple!

Spoiler

PreAndPostProcessorConfig.php:


<?php namespace ProcessWire;

class PreAndPostProcessorConfig extends ModuleConfig {

    public function __construct() {
        $this->add(array(
            array(
                'type' => 'Fieldset',
                'name' => '_compiler_conf',
                'label' => 'Compiler setup',
                'collapsed' => Inputfield::collapsedNo,
                'children' => array(
                    array(
                        'type' => 'select',
                        'name' => 'site_mode',
                        'label' => 'Set this to the mode how this site is used!',
                        #'description' => '',
                        'notes' => 'In production mode, the compiler ONLY get started if the output CSS-file is MISSING!',
                        'options' => array(
                            'PRODUCTION_MODE' => 'PRODUCTION_MODE',
                            'DEV_MODE' => 'DEV_MODE',
                        ),
                        'required' => true,
                        'columnWidth' => 100,
                    ),
                    array(
                        'type' => 'checkbox',
                        'name' => 'compiler_suppress_debugcomments',
                        'label' => 'Suppress SCSS-Source-Line_Numbers while in Debugmode',
                        'description' => 'When in Debugmode ($config->debug => true), the default behave is Nested output with SCSS-Source-Line_Numbers',
                        'notes' => 'Check this to override the default and select an output format below',
                        'showIf' => 'site_mode=DEV_MODE',
                        'columnWidth' => 100,
                    ),
                    array(
                        'type' => 'select',
                        'name' => 'compiler_output',
                        'label' => 'Select how the CSS should be generated',
                        'description' => '',
                        'notes' => 'default is: Nested',
                        'options' => array(
                            'Expanded' => 'Expanded',
                            'Nested' => 'Nested',
                            'Compact' => 'Compact',
                            'Compressed' => 'Compressed',
                            'Crunched' => 'Crunched'
                        ),
                        'required' => true,
                        'showIf' => 'site_mode=DEV_MODE, compiler_suppress_debugcomments=1',
                        'columnWidth' => 100,
                    ),
                )
            ),
            array(
                'type' => 'Fieldset',
                'name' => '_uikit_conf',
                'label' => 'Kit setup',
                'collapsed' => Inputfield::collapsedNo,
                'children' => array(
                    array(
                        'type' => 'select',
                        'name' => 'kit_type',
                        'label' => 'Select the Kit you are using',
                        #'description' => '',
                        'notes' => 'currently supported: uikit, (planned: bootstrap 4)',
                        'options' => array('uikit' => 'uikit'),
                        'value' => 'uikit',
                        'required' => true,
                        'columnWidth' => 50,
                    ),
                    array(
                        'type' => 'text',
                        'name' => 'kit_fullpath',
                        'label' => 'directory site path to your kits scss sources',
                        'description' => 'starts with "site/...", (your sitesfolder) without leading slash! But with trailing slash!',
                        'notes' => 'e.g.: site/templates/uikit/scss/ | must be writeable by PHP / PW!',
                        'placeholder' => 'site/templates/uikit/scss/',
                        'value' => '',
                        'required' => true,
                        'columnWidth' => 50,
                    ),
                    array(
                        'type' => 'text',
                        'name' => 'kit_variablesfilename',
                        'label' => 'Custom-Variablesfile (basename with extension)',
                        'description' => 'Relative to your scss kit start directory without leading slash!',
                        'notes' => 'e.g.: core/globalpwsettings.scss | must be writeable by PHP / PW!',
                        'placeholder' => 'core/globalpwsettings.scss',
                        'value' => '',
                        'required' => true,
                        'columnWidth' => 50,
                    ),
                    array(
                        'type' => 'text',
                        'name' => 'kit_startfilename',
                        'label' => 'startfile (basename with extension)',
                        'description' => 'Relative to your scss kit start directory without leading slash!',
                        'notes' => 'e.g.: uikit.scss',
                        'placeholder' => 'uikit.scss',
                        'value' => '',
                        'required' => true,
                        'columnWidth' => 50,
                    ),
                    array(
                        'type' => 'text',
                        'name' => 'kit_outputcssfile',
                        'label' => 'CSS-output-file (site path with extension!)',
                        'description' => 'starts with "site/...", (your sitesfolder) without leading slash!',
                        'notes' => 'e.g.: site/templates/styles/uikit.css | must be writeable by PHP / PW!',
                        'placeholder' => 'site/templates/styles/uikit.css',
                        'value' => '',
                        'required' => true,
                        'columnWidth' => 100,
                    ),
                )
            ),
        ));
    }
}

This is the complete config file! No other definitions or methods, also in the main module file are necessary. Unbelievable! :)

 

Another nice thing I discovered, is the use of the *.info.json files. So, this I have used before, but not like here. :)

The behave is like with the *Config.php files, - you write really less code, just arrays with key - value pairs and PW does the rest for you! Only difference here is, that you have to write it in JSON notation.

The ProcessPreProcessor.info.json file contains the neccessary and common parts: title, version, requires. And some others: permission, permissions, page and nav.

Page and nav are specific to Process modules. With page {name, parent, title} you define where PW should create you a page in the admin, and with nav, you can define a complete submenu for this page.

For those who are yet not familiar with the internal structure of Processmodules: you can navigate to a submenu entry by calling it: {pw-admin-url}/{main-module-url}/{submenu-url}/.

Calling the main menu url invokes the ___execute() method of the module. Calling a submenu url invoke the ___executeSubmenu() method. This all is really simple and straight forward. And it is really really helpful in cases like with the new toy for my toolbox. :)

The nav is a collection of arrays, each holding at least an url and a label. Thats enough for PW to implement the menu and submenu for you in the admin. But you also may define an icon too. Aaaand, you also can add your own custom key / value pairs to it. PW does not complain on it.

I have added a description. The nav was generated by parsing all core distribution scss files from the UIKit. They have a name and description in their first two lines. I programatically read this out and generated this nav notation for the info.json file:

Spoiler

ProcessPreProcessor.info.json:


{
    "title": "Process Pre-Processor",
    "summary": "",
    "version": 1,
    "author": "Horst Nogajski",
    "href": "",
    "icon": "",
    "requires": "ProcessWire>=3.0.18, PHP>=5.4.0, PreAndPostProcessor",
	"permission": "preprocessor",
	"permissions": {"preprocessor":"Run the Pre-Processor Config"},
	"page": {"name": "preprocessor", "parent": "setup", "title": "Pre-Processor"},
	"nav": 	[
                {"url":"globalpwsettings\/","label":"GlobalPWsettings","icon":"code","description":"Defines Sitewide Settings, also for other modules (LazySizes, etc)"},
                {"url":"alert\/","label":"Alert","icon":"code","description":"Defines styles for alert messages"},
                {"url":"animation\/","label":"Animation","icon":"code","description":"Provides a useful set of keyframe animations"},
                {"url":"article\/","label":"Article","icon":"code","description":"Defines styles for articles within your page"},
                {"url":"badge\/","label":"Badge","icon":"code","description":"Defines styles for badges"},
                {"url":"base\/","label":"Base","icon":"code","description":"Sets default values for HTML elements"},
                {"url":"block\/","label":"Block","icon":"code","description":"Defines styles to create horizontal layout blocks"},
                {"url":"breadcrumb\/","label":"Breadcrumb","icon":"code","description":"Defines styles for a breadcrumb navigation"},
                {"url":"button\/","label":"Button","icon":"code","description":"Defines styles for buttons"},
                {"url":"close\/","label":"Close","icon":"code","description":"Defines styles for a close button"},
                {"url":"column\/","label":"Column","icon":"code","description":"Provides a responsive, fluid and nestable columns for text and inline elements"},
                {"url":"comment\/","label":"Comment","icon":"code","description":"Defines styles for comment threads"},
                {"url":"contrast\/","label":"Contrast","icon":"code","description":"Utility class to adjust colors for dark or colored blocks"},
                {"url":"cover\/","label":"Cover","icon":"code","description":"Defines styles for images and videos to cover their container in a centered position"},
                {"url":"descriptionlist\/","label":"Descriptionlist","icon":"code","description":"Defines styles for description lists"},
                {"url":"dropdown\/","label":"Dropdown","icon":"code","description":"Defines styles for a toggleable dropdown"},
                {"url":"flex\/","label":"Flex","icon":"code","description":"Defines styles to create layouts with flexbox"},
                {"url":"form\/","label":"Form","icon":"code","description":"Defines styles for forms"},
                {"url":"grid\/","label":"Grid","icon":"code","description":"Provides a responsive, fluid and nestable grid"},
                {"url":"icon\/","label":"Icon","icon":"code","description":"Defines styles for icons"},
                {"url":"list\/","label":"List","icon":"code","description":"Defines styles for ordered and unordered lists"},
                {"url":"modal\/","label":"Modal","icon":"code","description":"Defines styles for modal dialogs"},
                {"url":"nav\/","label":"Nav","icon":"code","description":"Defines styles for list navigations"},
                {"url":"navbar\/","label":"Navbar","icon":"code","description":"Defines styles for the navigation bar"},
                {"url":"offcanvas\/","label":"Offcanvas","icon":"code","description":"Defines styles for an off-canvas sidebar that slides in and out of the page"},
                {"url":"overlay\/","label":"Overlay","icon":"code","description":"Defines styles for image overlays"},
                {"url":"pagination\/","label":"Pagination","icon":"code","description":"Defines styles for a navigation between pages"},
                {"url":"panel\/","label":"Panel","icon":"code","description":"Defines styles for reusable content areas"},
                {"url":"print\/","label":"Print","icon":"code","description":"Optimize page for printing"},
                {"url":"subnav\/","label":"Subnav","icon":"code","description":"Defines styles for the sub navigation"},
                {"url":"switcher\/","label":"Switcher","icon":"code","description":"Defines styles for the switcher"},
                {"url":"tab\/","label":"Tab","icon":"code","description":"Defines styles for a tabbed navigation"},
                {"url":"table\/","label":"Table","icon":"code","description":"Defines styles for tables"},
                {"url":"text\/","label":"Text","icon":"code","description":"Collection of useful text utility classes to style your content"},
                {"url":"thumbnail\/","label":"Thumbnail","icon":"code","description":"Defines styles for image thumbnails"},
                {"url":"thumbnav\/","label":"Thumbnav","icon":"code","description":"Defines styles for a thumbnail navigation"},
                {"url":"utility\/","label":"Utility","icon":"code","description":"Collection of useful utility classes to style your content"}
    ]
}

 

The (main) ___execute() method of the ProcessPreProcessor.module should present a submenu list with file infos. This now could be done by parsing the info.json file:

    public function ___execute() {
        // generate a navigation
        $dump = json_decode(file_get_contents(dirname(__FILE__) . '/' . basename(__FILE__, '.module') . '.info.json'));
        $nav  = $dump->nav;
        $out  = "\t\t\t<dl class='nav hnpp'>\n";
        foreach($nav as $obj) {
            $out .= "\t\t\t\t<dt><a href='./{$obj->url}'>{$obj->label}</a> ></dt>\n";
            $out .= "\t\t\t\t<dd>{$obj->description}</dd>\n";
        }
        $out .= "\t\t\t</dl>\n";
        return $out;
    }

 

To make it even more friendly for lazy devs, :), I created one method that is called from all sub-execute methods by simply passing their own name over into this function that loads and parse the scss file and displays its config page:

Spoiler

    public function ___executeGlobalPWsettings()  { return $this->run(__FUNCTION__); }  // Defines sitewide settings, also for other modules (LazySizes, etc)
    public function ___executeAlert()             { return $this->run(__FUNCTION__); }  // Defines styles for alert messages
    public function ___executeAnimation()         { return $this->run(__FUNCTION__); }  // Provides a useful set of keyframe animations
    public function ___executeArticle()           { return $this->run(__FUNCTION__); }  // Defines styles for articles within your page
    public function ___executeBadge()             { return $this->run(__FUNCTION__); }  // Defines styles for badges
    public function ___executeBase()              { return $this->run(__FUNCTION__); }  // Sets default values for HTML elements
    public function ___executeBlock()             { return $this->run(__FUNCTION__); }  // Defines styles to create horizontal layout blocks
    public function ___executeBreadcrumb()        { return $this->run(__FUNCTION__); }  // Defines styles for a breadcrumb navigation
    public function ___executeButton()            { return $this->run(__FUNCTION__); }  // Defines styles for buttons
    public function ___executeClose()             { return $this->run(__FUNCTION__); }  // Defines styles for a close button
    public function ___executeColumn()            { return $this->run(__FUNCTION__); }  // Provides a responsive, fluid and nestable columns for text and inline elements
    public function ___executeComment()           { return $this->run(__FUNCTION__); }  // Defines styles for comment threads
    public function ___executeContrast()          { return $this->run(__FUNCTION__); }  // Utility class to adjust colors for dark or colored blocks
    public function ___executeCover()             { return $this->run(__FUNCTION__); }  // Defines styles for images and videos to cover their container in a centered position
    public function ___executeDescriptionlist()   { return $this->run(__FUNCTION__); }  // Defines styles for description lists
    public function ___executeDropdown()          { return $this->run(__FUNCTION__); }  // Defines styles for a toggleable dropdown
    public function ___executeFlex()              { return $this->run(__FUNCTION__); }  // Defines styles to create layouts with flexbox
    public function ___executeForm()              { return $this->run(__FUNCTION__); }  // Defines styles for forms
    public function ___executeGrid()              { return $this->run(__FUNCTION__); }  // Provides a responsive, fluid and nestable grid
    public function ___executeIcon()              { return $this->run(__FUNCTION__); }  // Defines styles for icons
    public function ___executeList()              { return $this->run(__FUNCTION__); }  // Defines styles for ordered and unordered lists
    public function ___executeModal()             { return $this->run(__FUNCTION__); }  // Defines styles for modal dialogs
    public function ___executeNav()               { return $this->run(__FUNCTION__); }  // Defines styles for list navigations
    public function ___executeNavbar()            { return $this->run(__FUNCTION__); }  // Defines styles for the navigation bar
    public function ___executeOffcanvas()         { return $this->run(__FUNCTION__); }  // Defines styles for an off-canvas sidebar that slides in and out of the page
    public function ___executeOverlay()           { return $this->run(__FUNCTION__); }  // Defines styles for image overlays
    public function ___executePagination()        { return $this->run(__FUNCTION__); }  // Defines styles for a navigation between pages
    public function ___executePanel()             { return $this->run(__FUNCTION__); }  // Defines styles for reusable content areas
    public function ___executePrint()             { return $this->run(__FUNCTION__); }  // Optimize page for printing
    public function ___executeSubnav()            { return $this->run(__FUNCTION__); }  // Defines styles for the sub navigation
    public function ___executeSwitcher()          { return $this->run(__FUNCTION__); }  // Defines styles for the switcher
    public function ___executeTab()               { return $this->run(__FUNCTION__); }  // Defines styles for a tabbed navigation
    public function ___executeTable()             { return $this->run(__FUNCTION__); }  // Defines styles for tables
    public function ___executeText()              { return $this->run(__FUNCTION__); }  // Collection of useful text utility classes to style your content
    public function ___executeThumbnail()         { return $this->run(__FUNCTION__); }  // Defines styles for image thumbnails
    public function ___executeThumbnav()          { return $this->run(__FUNCTION__); }  // Defines styles for a thumbnail navigation
    public function ___executeUtility()           { return $this->run(__FUNCTION__); }  // Collection of useful utility classes to style your content

 

 

The first version work out nicely. Here is a screenshot of it:

 

uikit-configurator2.gif

 

... and to answer the initial question: Yes, it does!  :)

 

  • Like 17

Share this post


Link to post
Share on other sites

So we could build some profiles based on a supported frameworks  - ie: uiKit here - bundled with the module and play with it directly from PW ?

 

oh and WOW ! :o

  • Like 1

Share this post


Link to post
Share on other sites

thank you horst for the detailed insights!

how to you do all the scss compilation? any code snippets for that part? :)

  • Like 1

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Recently Browsing   0 members

    No registered users viewing this page.

  • Similar Content

    • By Robin S
      A community member raised a question and I thought a new sanitizer method for the purpose would be useful, hence...
      Sanitizer Transliterate
      Adds a transliterate method to $sanitizer that performs character replacements as defined in the module config. The default character replacements are based on the defaults from InputfieldPageName, but with uppercase characters included too.
      Usage
      Install the Sanitizer Transliterate module.
      Customise the character replacements in the module config as needed.
      Use the sanitizer on strings like so:
      $transliterated_string = $sanitizer->transliterate($string);
       
      https://github.com/Toutouwai/SanitizerTransliterate
      https://modules.processwire.com/modules/sanitizer-transliterate/
       
    • By dimitrios
      Hello,
      this module can publish content of a Processwire page on a Facebook page, triggered by saving the Processwire page.
      To set it up, configure the module with a Facebook app ID, secret and a Page ID. Following is additional configuration on Facebook for developers:
      Minimum Required Facebook App configuration:
      on Settings -> Basics, provide the App Domains, provide the Site URL, on Settings -> Advanced, set the API version to 2.10, add Product: Facebook Login, on Facebook Login -> Settings, set Client OAuth Login: Yes, set Web OAuth Login: Yes, set Enforce HTTPS: Yes, add "http://www.example.com/processwire/page/" to field Valid OAuth Redirect URIs. This module is configurable as follows:
      Templates: posts can take place only for pages with the defined templates. On/Off switch: specify a checkbox field that will not allow the post if checked. Specify a message and/or an image for the post.
      Usage
      edit the desired PW page and save; it will post right after the initial Facebook log in and permission granting. After that, an access token is kept.
       
      Download
      PW module directory: http://modules.processwire.com/modules/auto-fb-post/ Github: https://github.com/kastrind/AutoFbPost   Note: Facebook SDK for PHP is utilized.


    • By thomasaull
      I created a little helper module to trigger a CI pipeline when your website has been changed. It's quite simple and works like this: As soon as you save a page the module sets a Boolean via a pages save after hook. Once a day via LazyCron the module checks if the Boolean is set and sends a POST Request to a configurable Webhook URL.
      Some ideas to extend this:
      make request type configurable (GET, POST) make the module trigger at a specified time (probably only possible with a server cronjob) trigger manually Anything else? If there's interest, I might put in some more functionality. Let me know what you're interested in. Until then, maybe it is useful for a couple of people 🙂
      Github Repo: https://github.com/thomasaull/CiTrigger
    • By Robin S
      I created this module a while ago and never got around to publicising it, but it has been outed in the latest PW Weekly so here goes the support thread...
      Unique Image Variations
      Ensures that all ImageSizer options and focus settings affect image variation filenames.

      Background
      When using methods that produce image variations such as Pageimage::size(), ProcessWire includes some of the ImageSizer settings (height, width, cropping location, etc) in the variation filename. This is useful so that if you change these settings in your size() call a new variation is generated and you see this variation on the front-end.
      However, ProcessWire does not include several of the other ImageSizer settings in the variation filename:
      upscaling cropping, when set to false or a blank string interlace sharpening quality hidpi quality focus (whether any saved focus area for an image should affect cropping) focus data (the top/left/zoom data for the focus area) This means that if you change any of these settings, either in $config->imageSizerOptions or in an $options array passed to a method like size(), and you already have variations at the requested size/crop, then ProcessWire will not create new variations and will continue to serve the old variations. In other words you won't see the effect of your changed ImageSizer options on the front-end until you delete the old variations.
      Features
      The Unique Image Variations module ensures that any changes to ImageSizer options and any changes to the focus area made in Page Edit are reflected in the variation filename, so new variations will always be generated and displayed on the front-end.
      Installation
      Install the Unique Image Variations module.
      In the module config, set the ImageSizer options that you want to include in image variation filenames.
      Warnings
      Installing the module (and keeping one or more of the options selected in the module config) will cause all existing image variations to be regenerated the next time they are requested. If you have an existing website with a large number of images you may not want the performance impact of that. The module is perhaps best suited to new sites where image variations have not yet been generated.
      Similarly, if you change the module config settings on an existing site then all image variations will be regenerated the next time they are requested.
      If you think you might want to change an ImageSizer option in the future (I'm thinking here primarily of options such as interlace that are typically set in $config->imageSizerOptions) and would not want that change to cause existing image variations to be regenerated then best to not include that option in the module config after you first install the module.
       
      https://github.com/Toutouwai/UniqueImageVariations
      https://modules.processwire.com/modules/unique-image-variations/
    • By Sebi
      I've created a small module which lets you define a timestamp after which a page should be accessible. In addition you can define a timestamp when the release should end and the page should not be accessable any more.
      ProcessWire-Module: http://modules.processwire.com/modules/page-access-releasetime/
      Github: https://github.com/Sebiworld/PageAccessReleasetime
      Usage
      PageAccessReleasetime can be installed like every other module in ProcessWire. Check the following guide for detailed information: How-To Install or Uninstall Modules
      After that, you will find checkboxes for activating the releasetime-fields at the settings-tab of each page. You don't need to add the fields to your templates manually.
      Check e.g. the checkbox "Activate Releasetime from?" and fill in a date in the future. The page will not be accessable for your users until the given date is reached.
      If you have $config->pagefileSecure = true, the module will protect files of unreleased pages as well.
      How it works
      This module hooks into Page::viewable to prevent users to access unreleased pages:
      public function hookPageViewable($event) { $page = $event->object; $viewable = $event->return; if($viewable){ // If the page would be viewable, additionally check Releasetime and User-Permission $viewable = $this->canUserSee($page); } $event->return = $viewable; } To prevent access to the files of unreleased pages, we hook into Page::isPublic and ProcessPageView::sendFile.
      public function hookPageIsPublic($e) { $page = $e->object; if($e->return && $this->isReleaseTimeSet($page)) { $e->return = false; } } The site/assets/files/ directory of pages, which isPublic() returns false, will get a '-' as prefix. This indicates ProcessWire (with activated $config->pagefileSecure) to check the file's permissions via PHP before delivering it to the client.
      The check wether a not-public file should be accessable happens in ProcessPageView::sendFile. We throw an 404 Exception if the current user must not see the file.
      public function hookProcessPageViewSendFile($e) { $page = $e->arguments[0]; if(!$this->canUserSee($page)) { throw new Wire404Exception('File not found'); } } Additionally we hook into ProcessPageEdit::buildForm to add the PageAccessReleasetime fields to each page and move them to the settings tab.
      Limitations
      In the current version, releasetime-protected pages will appear in wire('pages')->find() queries. If you want to display a list of pages, where pages could be releasetime-protected, you should double-check with $page->viewable() wether the page can be accessed. $page->viewable() returns false, if the page is not released yet.
      If you have an idea how unreleased pages can be filtered out of ProcessWire selector queries, feel free to write an issue, comment or make a pull request!
×
×
  • Create New...