1641660425
CNRoom (Chats Noirs Room) is a header-only key-value database library using C++17 (std::filesystem
and std::variant
) and based on local files. It is actually in development by Fatih#6810 (accfldekur@gmail.com) from Moonlit Black Cats.
Installation
CNRoom is header-only, you just need a compiler that supports C++17 (std::filesystem
and std::variant
) then to include CNRoom/Room.hpp
after downloading files in the include directory. You may also need to link libstdc++fs
to your project in order to compile the std::filesystem
library that CNRoom uses.
Library vocabulary
I use the arrangement metaphor, you can imagine a room (base directory) with several drawers (file), inside these drawers you can tidy up papers (key) with informations written on them (values). CNRoom lets you assign several values of different types (std::string
, int
, double
, bool
) to a string called key and will write these values on a file of your choice (values are indexed in the order you write them). You can access to these values by the key.
Example code
A tutorial example code showing how easy CNRoom is to use!
//CNRoom
#include "CNRoom/Room.hpp"
//Standard
#include <iostream>
int main()
{
/// Stream class
////////////////////////////////////////////////////////////
CNRoom::Stream stream("database/lebgdu92.hkn", true); ///< Open a file, create new if doesn't exist
stream << CNRoom::Key{"mail", {"lebgdu92@gmail.com", true}}; ///< Write using <<
stream >> "mail"; ///< Read using >>
//Show method 1: std::get<Type>
std::cout << std::get<std::string>(stream()[0]) << std::endl; ///< Retreive key using () and value using []
stream.remove("mail"); ///< Remove a key
/// Room helper class
////////////////////////////////////////////////////////////
CNRoom::Room room;
room.connect("database", true); ///< Base directory (current path by default)
room.open("lebgdu92.hkn", [](auto& stream) ///< Open a file
{
stream.write({"sword", {"Sword of the Warrior", false, 4.85, 0}}); ///< Write using function write()
for(const auto& it: stream.read("sword").values) ///< Read using function read()
{
//Show method 2: Visit
std::visit([](auto const& value){ std::cout << value << ' '; }, it.standard());
}
}, true);
room.destroy("lebgdu92.hkn"); ///< Delete a file
/// Shortcut functions
////////////////////////////////////////////////////////////
room.quick_write("lebgdu92.hkn", {"sword", {"Sword of the Warrior", false, 4.85, 0}});
//Show method 3: Convert to string using Key::string()
std::cout << CNRoom::Key::string(room.quick_read("lebgdu92.hkn", "sword")[2]) << std::endl;
return 0;
}
Output:
lebgdu92@gmail.com
Sword of the Warrior 0 4.85 0 4.850000
Documentation
Struct and classes provided in CNRoom/Room.hpp
.
Class & members | Description |
---|---|
Variant | Class inheriting from std::variant and internally converting const char* to std::string if needed. |
Variant::standard() | Convert to standard std::variant . |
Struct & members | Description |
---|---|
Key | Struct that represents a key with a name and a vector of values. |
static Key::string(value) | Convert value to std::string. |
Key::name | Name of the key. |
Key::values | Vector of variant<string, int, double, bool>, access values with std::get, std::visit or Key::string. |
Key::operator[] | Access value by index. |
Class & members | Description |
---|---|
Stream | Stream class to operate on files. |
Stream::operator() | Returns a reference to the internal key. |
Stream::write(key) | Write a key. |
Stream::operator<< | Write a key. |
Stream::read(name) | Read a key by name. |
Stream::operator>> | Read a key by name. |
Stream::remove(name) | Remove a key. |
Some helper functions are provided in the Room class.
Class & members | Description |
---|---|
Room | Stream wrapper class. |
Room::connect(path) | Set the base directory. Optional, current path by default. |
Room::open(file, function) | Opens a file and call the given function. |
Room::exists(file) | Check if the given file exists. |
Room::destroy(file) | Delete a file. |
Room::quick_write(file, key) | Short way to write a key. |
Room::quick_read(file, name) | Short way to read a key. |
Performances
Can write and read keys of 5 values in a rate of 120 keys per second with my poor Toshiba DT01ACA100.
Download Details:
Author: swordfatih
Source Code: https://github.com/swordfatih/CNRoom
License: View license
1667425440
Perl script converts PDF files to Gerber format
Pdf2Gerb generates Gerber 274X photoplotting and Excellon drill files from PDFs of a PCB. Up to three PDFs are used: the top copper layer, the bottom copper layer (for 2-sided PCBs), and an optional silk screen layer. The PDFs can be created directly from any PDF drawing software, or a PDF print driver can be used to capture the Print output if the drawing software does not directly support output to PDF.
The general workflow is as follows:
Please note that Pdf2Gerb does NOT perform DRC (Design Rule Checks), as these will vary according to individual PCB manufacturer conventions and capabilities. Also note that Pdf2Gerb is not perfect, so the output files must always be checked before submitting them. As of version 1.6, Pdf2Gerb supports most PCB elements, such as round and square pads, round holes, traces, SMD pads, ground planes, no-fill areas, and panelization. However, because it interprets the graphical output of a Print function, there are limitations in what it can recognize (or there may be bugs).
See docs/Pdf2Gerb.pdf for install/setup, config, usage, and other info.
#Pdf2Gerb config settings:
#Put this file in same folder/directory as pdf2gerb.pl itself (global settings),
#or copy to another folder/directory with PDFs if you want PCB-specific settings.
#There is only one user of this file, so we don't need a custom package or namespace.
#NOTE: all constants defined in here will be added to main namespace.
#package pdf2gerb_cfg;
use strict; #trap undef vars (easier debug)
use warnings; #other useful info (easier debug)
##############################################################################################
#configurable settings:
#change values here instead of in main pfg2gerb.pl file
use constant WANT_COLORS => ($^O !~ m/Win/); #ANSI colors no worky on Windows? this must be set < first DebugPrint() call
#just a little warning; set realistic expectations:
#DebugPrint("${\(CYAN)}Pdf2Gerb.pl ${\(VERSION)}, $^O O/S\n${\(YELLOW)}${\(BOLD)}${\(ITALIC)}This is EXPERIMENTAL software. \nGerber files MAY CONTAIN ERRORS. Please CHECK them before fabrication!${\(RESET)}", 0); #if WANT_DEBUG
use constant METRIC => FALSE; #set to TRUE for metric units (only affect final numbers in output files, not internal arithmetic)
use constant APERTURE_LIMIT => 0; #34; #max #apertures to use; generate warnings if too many apertures are used (0 to not check)
use constant DRILL_FMT => '2.4'; #'2.3'; #'2.4' is the default for PCB fab; change to '2.3' for CNC
use constant WANT_DEBUG => 0; #10; #level of debug wanted; higher == more, lower == less, 0 == none
use constant GERBER_DEBUG => 0; #level of debug to include in Gerber file; DON'T USE FOR FABRICATION
use constant WANT_STREAMS => FALSE; #TRUE; #save decompressed streams to files (for debug)
use constant WANT_ALLINPUT => FALSE; #TRUE; #save entire input stream (for debug ONLY)
#DebugPrint(sprintf("${\(CYAN)}DEBUG: stdout %d, gerber %d, want streams? %d, all input? %d, O/S: $^O, Perl: $]${\(RESET)}\n", WANT_DEBUG, GERBER_DEBUG, WANT_STREAMS, WANT_ALLINPUT), 1);
#DebugPrint(sprintf("max int = %d, min int = %d\n", MAXINT, MININT), 1);
#define standard trace and pad sizes to reduce scaling or PDF rendering errors:
#This avoids weird aperture settings and replaces them with more standardized values.
#(I'm not sure how photoplotters handle strange sizes).
#Fewer choices here gives more accurate mapping in the final Gerber files.
#units are in inches
use constant TOOL_SIZES => #add more as desired
(
#round or square pads (> 0) and drills (< 0):
.010, -.001, #tiny pads for SMD; dummy drill size (too small for practical use, but needed so StandardTool will use this entry)
.031, -.014, #used for vias
.041, -.020, #smallest non-filled plated hole
.051, -.025,
.056, -.029, #useful for IC pins
.070, -.033,
.075, -.040, #heavier leads
# .090, -.043, #NOTE: 600 dpi is not high enough resolution to reliably distinguish between .043" and .046", so choose 1 of the 2 here
.100, -.046,
.115, -.052,
.130, -.061,
.140, -.067,
.150, -.079,
.175, -.088,
.190, -.093,
.200, -.100,
.220, -.110,
.160, -.125, #useful for mounting holes
#some additional pad sizes without holes (repeat a previous hole size if you just want the pad size):
.090, -.040, #want a .090 pad option, but use dummy hole size
.065, -.040, #.065 x .065 rect pad
.035, -.040, #.035 x .065 rect pad
#traces:
.001, #too thin for real traces; use only for board outlines
.006, #minimum real trace width; mainly used for text
.008, #mainly used for mid-sized text, not traces
.010, #minimum recommended trace width for low-current signals
.012,
.015, #moderate low-voltage current
.020, #heavier trace for power, ground (even if a lighter one is adequate)
.025,
.030, #heavy-current traces; be careful with these ones!
.040,
.050,
.060,
.080,
.100,
.120,
);
#Areas larger than the values below will be filled with parallel lines:
#This cuts down on the number of aperture sizes used.
#Set to 0 to always use an aperture or drill, regardless of size.
use constant { MAX_APERTURE => max((TOOL_SIZES)) + .004, MAX_DRILL => -min((TOOL_SIZES)) + .004 }; #max aperture and drill sizes (plus a little tolerance)
#DebugPrint(sprintf("using %d standard tool sizes: %s, max aper %.3f, max drill %.3f\n", scalar((TOOL_SIZES)), join(", ", (TOOL_SIZES)), MAX_APERTURE, MAX_DRILL), 1);
#NOTE: Compare the PDF to the original CAD file to check the accuracy of the PDF rendering and parsing!
#for example, the CAD software I used generated the following circles for holes:
#CAD hole size: parsed PDF diameter: error:
# .014 .016 +.002
# .020 .02267 +.00267
# .025 .026 +.001
# .029 .03167 +.00267
# .033 .036 +.003
# .040 .04267 +.00267
#This was usually ~ .002" - .003" too big compared to the hole as displayed in the CAD software.
#To compensate for PDF rendering errors (either during CAD Print function or PDF parsing logic), adjust the values below as needed.
#units are pixels; for example, a value of 2.4 at 600 dpi = .0004 inch, 2 at 600 dpi = .0033"
use constant
{
HOLE_ADJUST => -0.004 * 600, #-2.6, #holes seemed to be slightly oversized (by .002" - .004"), so shrink them a little
RNDPAD_ADJUST => -0.003 * 600, #-2, #-2.4, #round pads seemed to be slightly oversized, so shrink them a little
SQRPAD_ADJUST => +0.001 * 600, #+.5, #square pads are sometimes too small by .00067, so bump them up a little
RECTPAD_ADJUST => 0, #(pixels) rectangular pads seem to be okay? (not tested much)
TRACE_ADJUST => 0, #(pixels) traces seemed to be okay?
REDUCE_TOLERANCE => .001, #(inches) allow this much variation when reducing circles and rects
};
#Also, my CAD's Print function or the PDF print driver I used was a little off for circles, so define some additional adjustment values here:
#Values are added to X/Y coordinates; units are pixels; for example, a value of 1 at 600 dpi would be ~= .002 inch
use constant
{
CIRCLE_ADJUST_MINX => 0,
CIRCLE_ADJUST_MINY => -0.001 * 600, #-1, #circles were a little too high, so nudge them a little lower
CIRCLE_ADJUST_MAXX => +0.001 * 600, #+1, #circles were a little too far to the left, so nudge them a little to the right
CIRCLE_ADJUST_MAXY => 0,
SUBST_CIRCLE_CLIPRECT => FALSE, #generate circle and substitute for clip rects (to compensate for the way some CAD software draws circles)
WANT_CLIPRECT => TRUE, #FALSE, #AI doesn't need clip rect at all? should be on normally?
RECT_COMPLETION => FALSE, #TRUE, #fill in 4th side of rect when 3 sides found
};
#allow .012 clearance around pads for solder mask:
#This value effectively adjusts pad sizes in the TOOL_SIZES list above (only for solder mask layers).
use constant SOLDER_MARGIN => +.012; #units are inches
#line join/cap styles:
use constant
{
CAP_NONE => 0, #butt (none); line is exact length
CAP_ROUND => 1, #round cap/join; line overhangs by a semi-circle at either end
CAP_SQUARE => 2, #square cap/join; line overhangs by a half square on either end
CAP_OVERRIDE => FALSE, #cap style overrides drawing logic
};
#number of elements in each shape type:
use constant
{
RECT_SHAPELEN => 6, #x0, y0, x1, y1, count, "rect" (start, end corners)
LINE_SHAPELEN => 6, #x0, y0, x1, y1, count, "line" (line seg)
CURVE_SHAPELEN => 10, #xstart, ystart, x0, y0, x1, y1, xend, yend, count, "curve" (bezier 2 points)
CIRCLE_SHAPELEN => 5, #x, y, 5, count, "circle" (center + radius)
};
#const my %SHAPELEN =
#Readonly my %SHAPELEN =>
our %SHAPELEN =
(
rect => RECT_SHAPELEN,
line => LINE_SHAPELEN,
curve => CURVE_SHAPELEN,
circle => CIRCLE_SHAPELEN,
);
#panelization:
#This will repeat the entire body the number of times indicated along the X or Y axes (files grow accordingly).
#Display elements that overhang PCB boundary can be squashed or left as-is (typically text or other silk screen markings).
#Set "overhangs" TRUE to allow overhangs, FALSE to truncate them.
#xpad and ypad allow margins to be added around outer edge of panelized PCB.
use constant PANELIZE => {'x' => 1, 'y' => 1, 'xpad' => 0, 'ypad' => 0, 'overhangs' => TRUE}; #number of times to repeat in X and Y directions
# Set this to 1 if you need TurboCAD support.
#$turboCAD = FALSE; #is this still needed as an option?
#CIRCAD pad generation uses an appropriate aperture, then moves it (stroke) "a little" - we use this to find pads and distinguish them from PCB holes.
use constant PAD_STROKE => 0.3; #0.0005 * 600; #units are pixels
#convert very short traces to pads or holes:
use constant TRACE_MINLEN => .001; #units are inches
#use constant ALWAYS_XY => TRUE; #FALSE; #force XY even if X or Y doesn't change; NOTE: needs to be TRUE for all pads to show in FlatCAM and ViewPlot
use constant REMOVE_POLARITY => FALSE; #TRUE; #set to remove subtractive (negative) polarity; NOTE: must be FALSE for ground planes
#PDF uses "points", each point = 1/72 inch
#combined with a PDF scale factor of .12, this gives 600 dpi resolution (1/72 * .12 = 600 dpi)
use constant INCHES_PER_POINT => 1/72; #0.0138888889; #multiply point-size by this to get inches
# The precision used when computing a bezier curve. Higher numbers are more precise but slower (and generate larger files).
#$bezierPrecision = 100;
use constant BEZIER_PRECISION => 36; #100; #use const; reduced for faster rendering (mainly used for silk screen and thermal pads)
# Ground planes and silk screen or larger copper rectangles or circles are filled line-by-line using this resolution.
use constant FILL_WIDTH => .01; #fill at most 0.01 inch at a time
# The max number of characters to read into memory
use constant MAX_BYTES => 10 * M; #bumped up to 10 MB, use const
use constant DUP_DRILL1 => TRUE; #FALSE; #kludge: ViewPlot doesn't load drill files that are too small so duplicate first tool
my $runtime = time(); #Time::HiRes::gettimeofday(); #measure my execution time
print STDERR "Loaded config settings from '${\(__FILE__)}'.\n";
1; #last value must be truthful to indicate successful load
#############################################################################################
#junk/experiment:
#use Package::Constants;
#use Exporter qw(import); #https://perldoc.perl.org/Exporter.html
#my $caller = "pdf2gerb::";
#sub cfg
#{
# my $proto = shift;
# my $class = ref($proto) || $proto;
# my $settings =
# {
# $WANT_DEBUG => 990, #10; #level of debug wanted; higher == more, lower == less, 0 == none
# };
# bless($settings, $class);
# return $settings;
#}
#use constant HELLO => "hi there2"; #"main::HELLO" => "hi there";
#use constant GOODBYE => 14; #"main::GOODBYE" => 12;
#print STDERR "read cfg file\n";
#our @EXPORT_OK = Package::Constants->list(__PACKAGE__); #https://www.perlmonks.org/?node_id=1072691; NOTE: "_OK" skips short/common names
#print STDERR scalar(@EXPORT_OK) . " consts exported:\n";
#foreach(@EXPORT_OK) { print STDERR "$_\n"; }
#my $val = main::thing("xyz");
#print STDERR "caller gave me $val\n";
#foreach my $arg (@ARGV) { print STDERR "arg $arg\n"; }
Author: swannman
Source Code: https://github.com/swannman/pdf2gerb
License: GPL-3.0 license
1661577180
The following is a collection of tips I find to be useful when working with the Swift language. More content is available on my Twitter account!
Property Wrappers allow developers to wrap properties with specific behaviors, that will be seamlessly triggered whenever the properties are accessed.
While their primary use case is to implement business logic within our apps, it's also possible to use Property Wrappers as debugging tools!
For example, we could build a wrapper called @History
, that would be added to a property while debugging and would keep track of all the values set to this property.
import Foundation
@propertyWrapper
struct History<Value> {
private var value: Value
private(set) var history: [Value] = []
init(wrappedValue: Value) {
self.value = wrappedValue
}
var wrappedValue: Value {
get { value }
set {
history.append(value)
value = newValue
}
}
var projectedValue: Self {
return self
}
}
// We can then decorate our business code
// with the `@History` wrapper
struct User {
@History var name: String = ""
}
var user = User()
// All the existing call sites will still
// compile, without the need for any change
user.name = "John"
user.name = "Jane"
// But now we can also access an history of
// all the previous values!
user.$name.history // ["", "John"]
String
interpolationSwift 5 gave us the possibility to define our own custom String
interpolation methods.
This feature can be used to power many use cases, but there is one that is guaranteed to make sense in most projects: localizing user-facing strings.
import Foundation
extension String.StringInterpolation {
mutating func appendInterpolation(localized key: String, _ args: CVarArg...) {
let localized = String(format: NSLocalizedString(key, comment: ""), arguments: args)
appendLiteral(localized)
}
}
/*
Let's assume that this is the content of our Localizable.strings:
"welcome.screen.greetings" = "Hello %@!";
*/
let userName = "John"
print("\(localized: "welcome.screen.greetings", userName)") // Hello John!
structs
If you’ve always wanted to use some kind of inheritance mechanism for your structs, Swift 5.1 is going to make you very happy!
Using the new KeyPath-based dynamic member lookup, you can implement some pseudo-inheritance, where a type inherits the API of another one 🎉
(However, be careful, I’m definitely not advocating inheritance as a go-to solution 🙃)
import Foundation
protocol Inherits {
associatedtype SuperType
var `super`: SuperType { get }
}
extension Inherits {
subscript<T>(dynamicMember keyPath: KeyPath<SuperType, T>) -> T {
return self.`super`[keyPath: keyPath]
}
}
struct Person {
let name: String
}
@dynamicMemberLookup
struct User: Inherits {
let `super`: Person
let login: String
let password: String
}
let user = User(super: Person(name: "John Appleseed"), login: "Johnny", password: "1234")
user.name // "John Appleseed"
user.login // "Johnny"
NSAttributedString
through a Function BuilderSwift 5.1 introduced Function Builders: a great tool for building custom DSL syntaxes, like SwiftUI. However, one doesn't need to be building a full-fledged DSL in order to leverage them.
For example, it's possible to write a simple Function Builder, whose job will be to compose together individual instances of NSAttributedString
through a nicer syntax than the standard API.
import UIKit
@_functionBuilder
class NSAttributedStringBuilder {
static func buildBlock(_ components: NSAttributedString...) -> NSAttributedString {
let result = NSMutableAttributedString(string: "")
return components.reduce(into: result) { (result, current) in result.append(current) }
}
}
extension NSAttributedString {
class func composing(@NSAttributedStringBuilder _ parts: () -> NSAttributedString) -> NSAttributedString {
return parts()
}
}
let result = NSAttributedString.composing {
NSAttributedString(string: "Hello",
attributes: [.font: UIFont.systemFont(ofSize: 24),
.foregroundColor: UIColor.red])
NSAttributedString(string: " world!",
attributes: [.font: UIFont.systemFont(ofSize: 20),
.foregroundColor: UIColor.orange])
}
switch
and if
as expressionsContrary to other languages, like Kotlin, Swift does not allow switch
and if
to be used as expressions. Meaning that the following code is not valid Swift:
let constant = if condition {
someValue
} else {
someOtherValue
}
A common solution to this problem is to wrap the if
or switch
statement within a closure, that will then be immediately called. While this approach does manage to achieve the desired goal, it makes for a rather poor syntax.
To avoid the ugly trailing ()
and improve on the readability, you can define a resultOf
function, that will serve the exact same purpose, in a more elegant way.
import Foundation
func resultOf<T>(_ code: () -> T) -> T {
return code()
}
let randomInt = Int.random(in: 0...3)
let spelledOut: String = resultOf {
switch randomInt {
case 0:
return "Zero"
case 1:
return "One"
case 2:
return "Two"
case 3:
return "Three"
default:
return "Out of range"
}
}
print(spelledOut)
guard
statementsA guard
statement is a very convenient way for the developer to assert that a condition is met, in order for the execution of the program to keep going.
However, since the body of a guard
statement is meant to be executed when the condition evaluates to false
, the use of the negation (!
) operator within the condition of a guard
statement can make the code hard to read, as it becomes a double negative.
A nice trick to avoid such double negatives is to encapsulate the use of the !
operator within a new property or function, whose name does not include a negative.
import Foundation
extension Collection {
var hasElements: Bool {
return !isEmpty
}
}
let array = Bool.random() ? [1, 2, 3] : []
guard array.hasElements else { fatalError("array was empty") }
print(array)
init
without loosing the compiler-generated oneIt's common knowledge for Swift developers that, when you define a struct
, the compiler is going to automatically generate a memberwise init
for you. That is, unless you also define an init
of your own. Because then, the compiler won't generate any memberwise init
.
Yet, there are many instances where we might enjoy the opportunity to get both. As it turns out, this goal is quite easy to achieve: you just need to define your own init
in an extension
rather than inside the type definition itself.
import Foundation
struct Point {
let x: Int
let y: Int
}
extension Point {
init() {
x = 0
y = 0
}
}
let usingDefaultInit = Point(x: 4, y: 3)
let usingCustomInit = Point()
enum
Swift does not really have an out-of-the-box support of namespaces. One could argue that a Swift module can be seen as a namespace, but creating a dedicated Framework for this sole purpose can legitimately be regarded as overkill.
Some developers have taken the habit to use a struct
which only contains static
fields to implement a namespace. While this does the job, it requires us to remember to implement an empty private
init()
, because it wouldn't make sense for such a struct
to be instantiated.
It's actually possible to take this approach one step further, by replacing the struct
with an enum
. While it might seem weird to have an enum
with no case
, it's actually a very idiomatic way to declare a type that cannot be instantiated.
import Foundation
enum NumberFormatterProvider {
static var currencyFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.roundingIncrement = 0.01
return formatter
}
static var decimalFormatter: NumberFormatter {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.decimalSeparator = ","
return formatter
}
}
NumberFormatterProvider() // ❌ impossible to instantiate by mistake
NumberFormatterProvider.currencyFormatter.string(from: 2.456) // $2.46
NumberFormatterProvider.decimalFormatter.string(from: 2.456) // 2,456
Never
to represent impossible code pathsNever
is quite a peculiar type in the Swift Standard Library: it is defined as an empty enum enum Never { }
.
While this might seem odd at first glance, it actually yields a very interesting property: it makes it a type that cannot be constructed (i.e. it possesses no instances).
This way, Never
can be used as a generic parameter to let the compiler know that a particular feature will not be used.
import Foundation
enum Result<Value, Error> {
case success(value: Value)
case failure(error: Error)
}
func willAlwaysSucceed(_ completion: @escaping ((Result<String, Never>) -> Void)) {
completion(.success(value: "Call was successful"))
}
willAlwaysSucceed( { result in
switch result {
case .success(let value):
print(value)
// the compiler knows that the `failure` case cannot happen
// so it doesn't require us to handle it.
}
})
Decodable
enum
Swift's Codable
framework does a great job at seamlessly decoding entities from a JSON stream. However, when we integrate web-services, we are sometimes left to deal with JSONs that require behaviors that Codable
does not provide out-of-the-box.
For instance, we might have a string-based or integer-based enum
, and be required to set it to a default value when the data found in the JSON does not match any of its cases.
We might be tempted to implement this via an extensive switch
statement over all the possible cases, but there is a much shorter alternative through the initializer init?(rawValue:)
:
import Foundation
enum State: String, Decodable {
case active
case inactive
case undefined
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let decodedString = try container.decode(String.self)
self = State(rawValue: decodedString) ?? .undefined
}
}
let data = """
["active", "inactive", "foo"]
""".data(using: .utf8)!
let decoded = try! JSONDecoder().decode([State].self, from: data)
print(decoded) // [State.active, State.inactive, State.undefined]
Dependency injection boils down to a simple idea: when an object requires a dependency, it shouldn't create it by itself, but instead it should be given a function that does it for him.
Now the great thing with Swift is that, not only can a function take another function as a parameter, but that parameter can also be given a default value.
When you combine both those features, you can end up with a dependency injection pattern that is both lightweight on boilerplate, but also type safe.
import Foundation
protocol Service {
func call() -> String
}
class ProductionService: Service {
func call() -> String {
return "This is the production"
}
}
class MockService: Service {
func call() -> String {
return "This is a mock"
}
}
typealias Provider<T> = () -> T
class Controller {
let service: Service
init(serviceProvider: Provider<Service> = { return ProductionService() }) {
self.service = serviceProvider()
}
func work() {
print(service.call())
}
}
let productionController = Controller()
productionController.work() // prints "This is the production"
let mockedController = Controller(serviceProvider: { return MockService() })
mockedController.work() // prints "This is a mock"
Singletons are pretty bad. They make your architecture rigid and tightly coupled, which then results in your code being hard to test and refactor. Instead of using singletons, your code should rely on dependency injection, which is a much more architecturally sound approach.
But singletons are so easy to use, and dependency injection requires us to do extra-work. So maybe, for simple situations, we could find an in-between solution?
One possible solution is to rely on one of Swift's most know features: protocol-oriented programming. Using a protocol
, we declare and access our dependency. We then store it in a private singleton, and perform the injection through an extension of said protocol
.
This way, our code will indeed be decoupled from its dependency, while at the same time keeping the boilerplate to a minimum.
import Foundation
protocol Formatting {
var formatter: NumberFormatter { get }
}
private let sharedFormatter: NumberFormatter = {
let sharedFormatter = NumberFormatter()
sharedFormatter.numberStyle = .currency
return sharedFormatter
}()
extension Formatting {
var formatter: NumberFormatter { return sharedFormatter }
}
class ViewModel: Formatting {
var displayableAmount: String?
func updateDisplay(to amount: Double) {
displayableAmount = formatter.string(for: amount)
}
}
let viewModel = ViewModel()
viewModel.updateDisplay(to: 42000.45)
viewModel.displayableAmount // "$42,000.45"
[weak self]
and guard
Callbacks are a part of almost all iOS apps, and as frameworks such as RxSwift
keep gaining in popularity, they become ever more present in our codebase.
Seasoned Swift developers are aware of the potential memory leaks that @escaping
callbacks can produce, so they make real sure to always use [weak self]
, whenever they need to use self
inside such a context. And when they need to have self
be non-optional, they then add a guard
statement along.
Consequently, this syntax of a [weak self]
followed by a guard
rapidly tends to appear everywhere in the codebase. The good thing is that, through a little protocol-oriented trick, it's actually possible to get rid of this tedious syntax, without loosing any of its benefits!
import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true
protocol Weakifiable: class { }
extension Weakifiable {
func weakify(_ code: @escaping (Self) -> Void) -> () -> Void {
return { [weak self] in
guard let self = self else { return }
code(self)
}
}
func weakify<T>(_ code: @escaping (T, Self) -> Void) -> (T) -> Void {
return { [weak self] arg in
guard let self = self else { return }
code(arg, self)
}
}
}
extension NSObject: Weakifiable { }
class Producer: NSObject {
deinit {
print("deinit Producer")
}
private var handler: (Int) -> Void = { _ in }
func register(handler: @escaping (Int) -> Void) {
self.handler = handler
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0, execute: { self.handler(42) })
}
}
class Consumer: NSObject {
deinit {
print("deinit Consumer")
}
let producer = Producer()
func consume() {
producer.register(handler: weakify { result, strongSelf in
strongSelf.handle(result)
})
}
private func handle(_ result: Int) {
print("🎉 \(result)")
}
}
var consumer: Consumer? = Consumer()
consumer?.consume()
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: { consumer = nil })
// This code prints:
// 🎉 42
// deinit Consumer
// deinit Producer
Asynchronous functions are a big part of iOS APIs, and most developers are familiar with the challenge they pose when one needs to sequentially call several asynchronous APIs.
This often results in callbacks being nested into one another, a predicament often referred to as callback hell.
Many third-party frameworks are able to tackle this issue, for instance RxSwift or PromiseKit. Yet, for simple instances of the problem, there is no need to use such big guns, as it can actually be solved with simple function composition.
import Foundation
typealias CompletionHandler<Result> = (Result?, Error?) -> Void
infix operator ~>: MultiplicationPrecedence
func ~> <T, U>(_ first: @escaping (CompletionHandler<T>) -> Void, _ second: @escaping (T, CompletionHandler<U>) -> Void) -> (CompletionHandler<U>) -> Void {
return { completion in
first({ firstResult, error in
guard let firstResult = firstResult else { completion(nil, error); return }
second(firstResult, { (secondResult, error) in
completion(secondResult, error)
})
})
}
}
func ~> <T, U>(_ first: @escaping (CompletionHandler<T>) -> Void, _ transform: @escaping (T) -> U) -> (CompletionHandler<U>) -> Void {
return { completion in
first({ result, error in
guard let result = result else { completion(nil, error); return }
completion(transform(result), nil)
})
}
}
func service1(_ completionHandler: CompletionHandler<Int>) {
completionHandler(42, nil)
}
func service2(arg: String, _ completionHandler: CompletionHandler<String>) {
completionHandler("🎉 \(arg)", nil)
}
let chainedServices = service1
~> { int in return String(int / 2) }
~> service2
chainedServices({ result, _ in
guard let result = result else { return }
print(result) // Prints: 🎉 21
})
Asynchronous functions are a great way to deal with future events without blocking a thread. Yet, there are times where we would like them to behave in exactly such a blocking way.
Think about writing unit tests and using mocked network calls. You will need to add complexity to your test in order to deal with asynchronous functions, whereas synchronous ones would be much easier to manage.
Thanks to Swift proficiency in the functional paradigm, it is possible to write a function whose job is to take an asynchronous function and transform it into a synchronous one.
import Foundation
func makeSynchrone<A, B>(_ asyncFunction: @escaping (A, (B) -> Void) -> Void) -> (A) -> B {
return { arg in
let lock = NSRecursiveLock()
var result: B? = nil
asyncFunction(arg) {
result = $0
lock.unlock()
}
lock.lock()
return result!
}
}
func myAsyncFunction(arg: Int, completionHandler: (String) -> Void) {
completionHandler("🎉 \(arg)")
}
let syncFunction = makeSynchrone(myAsyncFunction)
print(syncFunction(42)) // prints 🎉 42
Closures are a great way to interact with generic APIs, for instance APIs that allow to manipulate data structures through the use of generic functions, such as filter()
or sorted()
.
The annoying part is that closures tend to clutter your code with many instances of {
, }
and $0
, which can quickly undermine its readably.
A nice alternative for a cleaner syntax is to use a KeyPath
instead of a closure, along with an operator that will deal with transforming the provided KeyPath
in a closure.
import Foundation
prefix operator ^
prefix func ^ <Element, Attribute>(_ keyPath: KeyPath<Element, Attribute>) -> (Element) -> Attribute {
return { element in element[keyPath: keyPath] }
}
struct MyData {
let int: Int
let string: String
}
let data = [MyData(int: 2, string: "Foo"), MyData(int: 4, string: "Bar")]
data.map(^\.int) // [2, 4]
data.map(^\.string) // ["Foo", "Bar"]
userInfo
Dictionary
Many iOS APIs still rely on a userInfo
Dictionary
to handle use-case specific data. This Dictionary
usually stores untyped values, and is declared as follows: [String: Any]
(or sometimes [AnyHashable: Any]
.
Retrieving data from such a structure will involve some conditional casting (via the as?
operator), which is prone to both errors and repetitions. Yet, by introducing a custom subscript
, it's possible to encapsulate all the tedious logic, and end-up with an easier and more robust API.
import Foundation
typealias TypedUserInfoKey<T> = (key: String, type: T.Type)
extension Dictionary where Key == String, Value == Any {
subscript<T>(_ typedKey: TypedUserInfoKey<T>) -> T? {
return self[typedKey.key] as? T
}
}
let userInfo: [String : Any] = ["Foo": 4, "Bar": "forty-two"]
let integerTypedKey = TypedUserInfoKey(key: "Foo", type: Int.self)
let intValue = userInfo[integerTypedKey] // returns 4
type(of: intValue) // returns Int?
let stringTypedKey = TypedUserInfoKey(key: "Bar", type: String.self)
let stringValue = userInfo[stringTypedKey] // returns "forty-two"
type(of: stringValue) // returns String?
MVVM is a great pattern to separate business logic from presentation logic. The main challenge to make it work, is to define a mechanism for the presentation layer to be notified of model updates.
RxSwift is a perfect choice to solve such a problem. Yet, some developers don't feel confortable with leveraging a third-party library for such a central part of their architecture.
For those situation, it's possible to define a lightweight Variable
type, that will make the MVVM pattern very easy to use!
import Foundation
class Variable<Value> {
var value: Value {
didSet {
onUpdate?(value)
}
}
var onUpdate: ((Value) -> Void)? {
didSet {
onUpdate?(value)
}
}
init(_ value: Value, _ onUpdate: ((Value) -> Void)? = nil) {
self.value = value
self.onUpdate = onUpdate
self.onUpdate?(value)
}
}
let variable: Variable<String?> = Variable(nil)
variable.onUpdate = { data in
if let data = data {
print(data)
}
}
variable.value = "Foo"
variable.value = "Bar"
// prints:
// Foo
// Bar
typealias
to its fullestThe keyword typealias
allows developers to give a new name to an already existing type. For instance, Swift defines Void
as a typealias
of ()
, the empty tuple.
But a less known feature of this mechanism is that it allows to assign concrete types for generic parameters, or to rename them. This can help make the semantics of generic types much clearer, when used in specific use cases.
import Foundation
enum Either<Left, Right> {
case left(Left)
case right(Right)
}
typealias Result<Value> = Either<Value, Error>
typealias IntOrString = Either<Int, String>
forEach
Iterating through objects via the forEach(_:)
method is a great alternative to the classic for
loop, as it allows our code to be completely oblivious of the iteration logic. One limitation, however, is that forEach(_:)
does not allow to stop the iteration midway.
Taking inspiration from the Objective-C implementation, we can write an overload that will allow the developer to stop the iteration, if needed.
import Foundation
extension Sequence {
func forEach(_ body: (Element, _ stop: inout Bool) throws -> Void) rethrows {
var stop = false
for element in self {
try body(element, &stop)
if stop {
return
}
}
}
}
["Foo", "Bar", "FooBar"].forEach { element, stop in
print(element)
stop = (element == "Bar")
}
// Prints:
// Foo
// Bar
reduce()
Functional programing is a great way to simplify a codebase. For instance, reduce
is an alternative to the classic for
loop, without most the boilerplate. Unfortunately, simplicity often comes at the price of performance.
Consider that you want to remove duplicate values from a Sequence
. While reduce()
is a perfectly fine way to express this computation, the performance will be sub optimal, because of all the unnecessary Array
copying that will happen every time its closure gets called.
That's when reduce(into:_:)
comes into play. This version of reduce
leverages the capacities of copy-on-write type (such as Array
or Dictionnary
) in order to avoid unnecessary copying, which results in a great performance boost.
import Foundation
func time(averagedExecutions: Int = 1, _ code: () -> Void) {
let start = Date()
for _ in 0..<averagedExecutions { code() }
let end = Date()
let duration = end.timeIntervalSince(start) / Double(averagedExecutions)
print("time: \(duration)")
}
let data = (1...1_000).map { _ in Int(arc4random_uniform(256)) }
// runs in 0.63s
time {
let noDuplicates: [Int] = data.reduce([], { $0.contains($1) ? $0 : $0 + [$1] })
}
// runs in 0.15s
time {
let noDuplicates: [Int] = data.reduce(into: [], { if !$0.contains($1) { $0.append($1) } } )
}
UI components such as UITableView
and UICollectionView
rely on reuse identifiers in order to efficiently recycle the views they display. Often, those reuse identifiers take the form of a static hardcoded String
, that will be used for every instance of their class.
Through protocol-oriented programing, it's possible to avoid those hardcoded values, and instead use the name of the type as a reuse identifier.
import Foundation
import UIKit
protocol Reusable {
static var reuseIdentifier: String { get }
}
extension Reusable {
static var reuseIdentifier: String {
return String(describing: self)
}
}
extension UITableViewCell: Reusable { }
extension UITableView {
func register<T: UITableViewCell>(_ class: T.Type) {
register(`class`, forCellReuseIdentifier: T.reuseIdentifier)
}
func dequeueReusableCell<T: UITableViewCell>(for indexPath: IndexPath) -> T {
return dequeueReusableCell(withIdentifier: T.reuseIdentifier, for: indexPath) as! T
}
}
class MyCell: UITableViewCell { }
let tableView = UITableView()
tableView.register(MyCell.self)
let myCell: MyCell = tableView.dequeueReusableCell(for: [0, 0])
The C language has a construct called union
, that allows a single variable to hold values from different types. While Swift does not provide such a construct, it provides enums with associated values, which allows us to define a type called Either
that implements a union
of two types.
import Foundation
enum Either<A, B> {
case left(A)
case right(B)
func either(ifLeft: ((A) -> Void)? = nil, ifRight: ((B) -> Void)? = nil) {
switch self {
case let .left(a):
ifLeft?(a)
case let .right(b):
ifRight?(b)
}
}
}
extension Bool { static func random() -> Bool { return arc4random_uniform(2) == 0 } }
var intOrString: Either<Int, String> = Bool.random() ? .left(2) : .right("Foo")
intOrString.either(ifLeft: { print($0 + 1) }, ifRight: { print($0 + "Bar") })
If you're interested by this kind of data structure, I strongly recommend that you learn more about Algebraic Data Types.
Most of the time, when we create a .xib
file, we give it the same name as its associated class. From that, if we later refactor our code and rename such a class, we run the risk of forgetting to rename the associated .xib
.
While the error will often be easy to catch, if the .xib
is used in a remote section of its app, it might go unnoticed for sometime. Fortunately it's possible to build custom test predicates that will assert that 1) for a given class, there exists a .nib
with the same name in a given Bundle
, 2) for all the .nib
in a given Bundle
, there exists a class with the same name.
import XCTest
public func XCTAssertClassHasNib(_ class: AnyClass, bundle: Bundle, file: StaticString = #file, line: UInt = #line) {
let associatedNibURL = bundle.url(forResource: String(describing: `class`), withExtension: "nib")
XCTAssertNotNil(associatedNibURL, "Class \"\(`class`)\" has no associated nib file", file: file, line: line)
}
public func XCTAssertNibHaveClasses(_ bundle: Bundle, file: StaticString = #file, line: UInt = #line) {
guard let bundleName = bundle.infoDictionary?["CFBundleName"] as? String,
let basePath = bundle.resourcePath,
let enumerator = FileManager.default.enumerator(at: URL(fileURLWithPath: basePath),
includingPropertiesForKeys: nil,
options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants]) else { return }
var nibFilesURLs = [URL]()
for case let fileURL as URL in enumerator {
if fileURL.pathExtension.uppercased() == "NIB" {
nibFilesURLs.append(fileURL)
}
}
nibFilesURLs.map { $0.lastPathComponent }
.compactMap { $0.split(separator: ".").first }
.map { String($0) }
.forEach {
let associatedClass: AnyClass? = bundle.classNamed("\(bundleName).\($0)")
XCTAssertNotNil(associatedClass, "File \"\($0).nib\" has no associated class", file: file, line: line)
}
}
XCTAssertClassHasNib(MyFirstTableViewCell.self, bundle: Bundle(for: AppDelegate.self))
XCTAssertClassHasNib(MySecondTableViewCell.self, bundle: Bundle(for: AppDelegate.self))
XCTAssertNibHaveClasses(Bundle(for: AppDelegate.self))
Many thanks Benjamin Lavialle for coming up with the idea behind the second test predicate.
Seasoned Swift developers know it: a protocol with associated type (PAT) "can only be used as a generic constraint because it has Self or associated type requirements". When we really need to use a PAT to type a variable, the goto workaround is to use a type-erased wrapper.
While this solution works perfectly, it requires a fair amount of boilerplate code. In instances where we are only interested in exposing one particular function of the PAT, a shorter approach using function types is possible.
import Foundation
import UIKit
protocol Configurable {
associatedtype Model
func configure(with model: Model)
}
typealias Configurator<Model> = (Model) -> ()
extension UILabel: Configurable {
func configure(with model: String) {
self.text = model
}
}
let label = UILabel()
let configurator: Configurator<String> = label.configure
configurator("Foo")
label.text // "Foo"
UIKit
exposes a very powerful and simple API to perform view animations. However, this API can become a little bit quirky to use when we want to perform animations sequentially, because it involves nesting closure within one another, which produces notoriously hard to maintain code.
Nonetheless, it's possible to define a rather simple class, that will expose a really nicer API for this particular use case 👌
import Foundation
import UIKit
class AnimationSequence {
typealias Animations = () -> Void
private let current: Animations
private let duration: TimeInterval
private var next: AnimationSequence? = nil
init(animations: @escaping Animations, duration: TimeInterval) {
self.current = animations
self.duration = duration
}
@discardableResult func append(animations: @escaping Animations, duration: TimeInterval) -> AnimationSequence {
var lastAnimation = self
while let nextAnimation = lastAnimation.next {
lastAnimation = nextAnimation
}
lastAnimation.next = AnimationSequence(animations: animations, duration: duration)
return self
}
func run() {
UIView.animate(withDuration: duration, animations: current, completion: { finished in
if finished, let next = self.next {
next.run()
}
})
}
}
var firstView = UIView()
var secondView = UIView()
firstView.alpha = 0
secondView.alpha = 0
AnimationSequence(animations: { firstView.alpha = 1.0 }, duration: 1)
.append(animations: { secondView.alpha = 1.0 }, duration: 0.5)
.append(animations: { firstView.alpha = 0.0 }, duration: 2.0)
.run()
Debouncing is a very useful tool when dealing with UI inputs. Consider a search bar, whose content is used to query an API. It wouldn't make sense to perform a request for every character the user is typing, because as soon as a new character is entered, the result of the previous request has become irrelevant.
Instead, our code will perform much better if we "debounce" the API call, meaning that we will wait until some delay has passed, without the input being modified, before actually performing the call.
import Foundation
func debounced(delay: TimeInterval, queue: DispatchQueue = .main, action: @escaping (() -> Void)) -> () -> Void {
var workItem: DispatchWorkItem?
return {
workItem?.cancel()
workItem = DispatchWorkItem(block: action)
queue.asyncAfter(deadline: .now() + delay, execute: workItem!)
}
}
let debouncedPrint = debounced(delay: 1.0) { print("Action performed!") }
debouncedPrint()
debouncedPrint()
debouncedPrint()
// After a 1 second delay, this gets
// printed only once to the console:
// Action performed!
Optional
booleansWhen we need to apply the standard boolean operators to Optional
booleans, we often end up with a syntax unnecessarily crowded with unwrapping operations. By taking a cue from the world of three-valued logics, we can define a couple operators that make working with Bool?
values much nicer.
import Foundation
func && (lhs: Bool?, rhs: Bool?) -> Bool? {
switch (lhs, rhs) {
case (false, _), (_, false):
return false
case let (unwrapLhs?, unwrapRhs?):
return unwrapLhs && unwrapRhs
default:
return nil
}
}
func || (lhs: Bool?, rhs: Bool?) -> Bool? {
switch (lhs, rhs) {
case (true, _), (_, true):
return true
case let (unwrapLhs?, unwrapRhs?):
return unwrapLhs || unwrapRhs
default:
return nil
}
}
false && nil // false
true && nil // nil
[true, nil, false].reduce(true, &&) // false
nil || true // true
nil || false // nil
[true, nil, false].reduce(false, ||) // true
Sequence
Transforming a Sequence
in order to remove all the duplicate values it contains is a classic use case. To implement it, one could be tempted to transform the Sequence
into a Set
, then back to an Array
. The downside with this approach is that it will not preserve the order of the sequence, which can definitely be a dealbreaker. Using reduce()
it is possible to provide a concise implementation that preserves ordering:
import Foundation
extension Sequence where Element: Equatable {
func duplicatesRemoved() -> [Element] {
return reduce([], { $0.contains($1) ? $0 : $0 + [$1] })
}
}
let data = [2, 5, 2, 3, 6, 5, 2]
data.duplicatesRemoved() // [2, 5, 3, 6]
Optional strings are very common in Swift code, for instance many objects from UIKit
expose the text they display as a String?
. Many times you will need to manipulate this data as an unwrapped String
, with a default value set to the empty string for nil
cases.
While the nil-coalescing operator (e.g. ??
) is a perfectly fine way to a achieve this goal, defining a computed variable like orEmpty
can help a lot in cleaning the syntax.
import Foundation
import UIKit
extension Optional where Wrapped == String {
var orEmpty: String {
switch self {
case .some(let value):
return value
case .none:
return ""
}
}
}
func doesNotWorkWithOptionalString(_ param: String) {
// do something with `param`
}
let label = UILabel()
label.text = "This is some text."
doesNotWorkWithOptionalString(label.text.orEmpty)
Every seasoned iOS developers knows it: objects from UIKit
can only be accessed from the main thread. Any attempt to access them from a background thread is a guaranteed crash.
Still, running a costly computation on the background, and then using it to update the UI can be a common pattern.
In such cases you can rely on asyncUI
to encapsulate all the boilerplate code.
import Foundation
import UIKit
func asyncUI<T>(_ computation: @autoclosure @escaping () -> T, qos: DispatchQoS.QoSClass = .userInitiated, _ completion: @escaping (T) -> Void) {
DispatchQueue.global(qos: qos).async {
let value = computation()
DispatchQueue.main.async {
completion(value)
}
}
}
let label = UILabel()
func costlyComputation() -> Int { return (0..<10_000).reduce(0, +) }
asyncUI(costlyComputation()) { value in
label.text = "\(value)"
}
A debug view, from which any controller of an app can be instantiated and pushed on the navigation stack, has the potential to bring some real value to a development process. A requirement to build such a view is to have a list of all the classes from a given Bundle
that inherit from UIViewController
. With the following extension
, retrieving this list becomes a piece of cake 🍰
import Foundation
import UIKit
import ObjectiveC
extension Bundle {
func viewControllerTypes() -> [UIViewController.Type] {
guard let bundlePath = self.executablePath else { return [] }
var size: UInt32 = 0
var rawClassNames: UnsafeMutablePointer<UnsafePointer<Int8>>!
var parsedClassNames = [String]()
rawClassNames = objc_copyClassNamesForImage(bundlePath, &size)
for index in 0..<size {
let className = rawClassNames[Int(index)]
if let name = NSString.init(utf8String:className) as String?,
NSClassFromString(name) is UIViewController.Type {
parsedClassNames.append(name)
}
}
return parsedClassNames
.sorted()
.compactMap { NSClassFromString($0) as? UIViewController.Type }
}
}
// Fetch all view controller types in UIKit
Bundle(for: UIViewController.self).viewControllerTypes()
I share the credit for this tip with Benoît Caron.
Update As it turns out, map
is actually a really bad name for this function, because it does not preserve composition of transformations, a property that is required to fit the definition of a real map
function.
Surprisingly enough, the standard library doesn't define a map()
function for dictionaries that allows to map both keys
and values
into a new Dictionary
. Nevertheless, such a function can be helpful, for instance when converting data across different frameworks.
import Foundation
extension Dictionary {
func map<T: Hashable, U>(_ transform: (Key, Value) throws -> (T, U)) rethrows -> [T: U] {
var result: [T: U] = [:]
for (key, value) in self {
let (transformedKey, transformedValue) = try transform(key, value)
result[transformedKey] = transformedValue
}
return result
}
}
let data = [0: 5, 1: 6, 2: 7]
data.map { ("\($0)", $1 * $1) } // ["2": 49, "0": 25, "1": 36]
nil
valuesSwift provides the function compactMap()
, that can be used to remove nil
values from a Sequence
of optionals when calling it with an argument that just returns its parameter (i.e. compactMap { $0 }
). Still, for such use cases it would be nice to get rid of the trailing closure.
The implementation isn't as straightforward as your usual extension
, but once it has been written, the call site definitely gets cleaner 👌
import Foundation
protocol OptionalConvertible {
associatedtype Wrapped
func asOptional() -> Wrapped?
}
extension Optional: OptionalConvertible {
func asOptional() -> Wrapped? {
return self
}
}
extension Sequence where Element: OptionalConvertible {
func compacted() -> [Element.Wrapped] {
return compactMap { $0.asOptional() }
}
}
let data = [nil, 1, 2, nil, 3, 5, nil, 8, nil]
data.compacted() // [1, 2, 3, 5, 8]
It might happen that your code has to deal with values that come with an expiration date. In a game, it could be a score multiplier that will only last for 30 seconds. Or it could be an authentication token for an API, with a 15 minutes lifespan. In both instances you can rely on the type Expirable
to encapsulate the expiration logic.
import Foundation
struct Expirable<T> {
private var innerValue: T
private(set) var expirationDate: Date
var value: T? {
return hasExpired() ? nil : innerValue
}
init(value: T, expirationDate: Date) {
self.innerValue = value
self.expirationDate = expirationDate
}
init(value: T, duration: Double) {
self.innerValue = value
self.expirationDate = Date().addingTimeInterval(duration)
}
func hasExpired() -> Bool {
return expirationDate < Date()
}
}
let expirable = Expirable(value: 42, duration: 3)
sleep(2)
expirable.value // 42
sleep(2)
expirable.value // nil
I share the credit for this tip with Benoît Caron.
map()
Almost all Apple devices able to run Swift code are powered by a multi-core CPU, consequently making a good use of parallelism is a great way to improve code performance. map()
is a perfect candidate for such an optimization, because it is almost trivial to define a parallel implementation.
import Foundation
extension Array {
func parallelMap<T>(_ transform: (Element) -> T) -> [T] {
let res = UnsafeMutablePointer<T>.allocate(capacity: count)
DispatchQueue.concurrentPerform(iterations: count) { i in
res[i] = transform(self[i])
}
let finalResult = Array<T>(UnsafeBufferPointer(start: res, count: count))
res.deallocate(capacity: count)
return finalResult
}
}
let array = (0..<1_000).map { $0 }
func work(_ n: Int) -> Int {
return (0..<n).reduce(0, +)
}
array.parallelMap { work($0) }
🚨 Make sure to only use parallelMap()
when the transform
function actually performs some costly computations. Otherwise performances will be systematically slower than using map()
, because of the multithreading overhead.
During development of a feature that performs some heavy computations, it can be helpful to measure just how much time a chunk of code takes to run. The time()
function is a nice tool for this purpose, because of how simple it is to add and then to remove when it is no longer needed.
import Foundation
func time(averagedExecutions: Int = 1, _ code: () -> Void) {
let start = Date()
for _ in 0..<averagedExecutions { code() }
let end = Date()
let duration = end.timeIntervalSince(start) / Double(averagedExecutions)
print("time: \(duration)")
}
time {
(0...10_000).map { $0 * $0 }
}
// time: 0.183973908424377
Concurrency is definitely one of those topics were the right encapsulation bears the potential to make your life so much easier. For instance, with this piece of code you can easily launch two computations in parallel, and have the results returned in a tuple.
import Foundation
func parallel<T, U>(_ left: @autoclosure () -> T, _ right: @autoclosure () -> U) -> (T, U) {
var leftRes: T?
var rightRes: U?
DispatchQueue.concurrentPerform(iterations: 2, execute: { id in
if id == 0 {
leftRes = left()
} else {
rightRes = right()
}
})
return (leftRes!, rightRes!)
}
let values = (1...100_000).map { $0 }
let results = parallel(values.map { $0 * $0 }, values.reduce(0, +))
Swift exposes three special variables #file
, #line
and #function
, that are respectively set to the name of the current file, line and function. Those variables become very useful when writing custom logging functions or test predicates.
import Foundation
func log(_ message: String, _ file: String = #file, _ line: Int = #line, _ function: String = #function) {
print("[\(file):\(line)] \(function) - \(message)")
}
func foo() {
log("Hello world!")
}
foo() // [MyPlayground.playground:8] foo() - Hello world!
Swift 4.1 has introduced a new feature called Conditional Conformance, which allows a type to implement a protocol only when its generic type also does.
With this addition it becomes easy to let Optional
implement Comparable
only when Wrapped
also implements Comparable
:
import Foundation
extension Optional: Comparable where Wrapped: Comparable {
public static func < (lhs: Optional, rhs: Optional) -> Bool {
switch (lhs, rhs) {
case let (lhs?, rhs?):
return lhs < rhs
case (nil, _?):
return true // anything is greater than nil
case (_?, nil):
return false // nil in smaller than anything
case (nil, nil):
return true // nil is not smaller than itself
}
}
}
let data: [Int?] = [8, 4, 3, nil, 12, 4, 2, nil, -5]
data.sorted() // [nil, nil, Optional(-5), Optional(2), Optional(3), Optional(4), Optional(4), Optional(8), Optional(12)]
Any attempt to access an Array
beyond its bounds will result in a crash. While it's possible to write conditions such as if index < array.count { array[index] }
in order to prevent such crashes, this approach will rapidly become cumbersome.
A great thing is that this condition can be encapsulated in a custom subscript
that will work on any Collection
:
import Foundation
extension Collection {
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
let data = [1, 3, 4]
data[safe: 1] // Optional(3)
data[safe: 10] // nil
Subscripting a string with a range can be very cumbersome in Swift 4. Let's face it, no one wants to write lines like someString[index(startIndex, offsetBy: 0)..<index(startIndex, offsetBy: 10)]
on a regular basis.
Luckily, with the addition of one clever extension, strings can be sliced as easily as arrays 🎉
import Foundation
extension String {
public subscript(value: CountableClosedRange<Int>) -> Substring {
get {
return self[index(startIndex, offsetBy: value.lowerBound)...index(startIndex, offsetBy: value.upperBound)]
}
}
public subscript(value: CountableRange<Int>) -> Substring {
get {
return self[index(startIndex, offsetBy: value.lowerBound)..<index(startIndex, offsetBy: value.upperBound)]
}
}
public subscript(value: PartialRangeUpTo<Int>) -> Substring {
get {
return self[..<index(startIndex, offsetBy: value.upperBound)]
}
}
public subscript(value: PartialRangeThrough<Int>) -> Substring {
get {
return self[...index(startIndex, offsetBy: value.upperBound)]
}
}
public subscript(value: PartialRangeFrom<Int>) -> Substring {
get {
return self[index(startIndex, offsetBy: value.lowerBound)...]
}
}
}
let data = "This is a string!"
data[..<4] // "This"
data[5..<9] // "is a"
data[10...] // "string!"
By using a KeyPath
along with a generic type, a very clean and concise syntax for sorting data can be implemented:
import Foundation
extension Sequence {
func sorted<T: Comparable>(by attribute: KeyPath<Element, T>) -> [Element] {
return sorted(by: { $0[keyPath: attribute] < $1[keyPath: attribute] })
}
}
let data = ["Some", "words", "of", "different", "lengths"]
data.sorted(by: \.count) // ["of", "Some", "words", "lengths", "different"]
If you like this syntax, make sure to checkout KeyPathKit!
By capturing a local variable in a returned closure, it is possible to manufacture cache-efficient versions of pure functions. Be careful though, this trick only works with non-recursive function!
import Foundation
func cached<In: Hashable, Out>(_ f: @escaping (In) -> Out) -> (In) -> Out {
var cache = [In: Out]()
return { (input: In) -> Out in
if let cachedValue = cache[input] {
return cachedValue
} else {
let result = f(input)
cache[input] = result
return result
}
}
}
let cachedCos = cached { (x: Double) in cos(x) }
cachedCos(.pi * 2) // value of cos for 2π is now cached
When distinguishing between complex boolean conditions, using a switch
statement along with pattern matching can be more readable than the classic series of if {} else if {}
.
import Foundation
let expr1: Bool
let expr2: Bool
let expr3: Bool
if expr1 && !expr3 {
functionA()
} else if !expr2 && expr3 {
functionB()
} else if expr1 && !expr2 && expr3 {
functionC()
}
switch (expr1, expr2, expr3) {
case (true, _, false):
functionA()
case (_, false, true):
functionB()
case (true, false, true):
functionC()
default:
break
}
Using map()
on a range makes it easy to generate an array of data.
import Foundation
func randomInt() -> Int { return Int(arc4random()) }
let randomArray = (1...10).map { _ in randomInt() }
Using @autoclosure
enables the compiler to automatically wrap an argument within a closure, thus allowing for a very clean syntax at call sites.
import UIKit
extension UIView {
class func animate(withDuration duration: TimeInterval, _ animations: @escaping @autoclosure () -> Void) {
UIView.animate(withDuration: duration, animations: animations)
}
}
let view = UIView()
UIView.animate(withDuration: 0.3, view.backgroundColor = .orange)
When working with RxSwift, it's very easy to observe both the current and previous value of an observable sequence by simply introducing a shift using skip()
.
import RxSwift
let values = Observable.of(4, 8, 15, 16, 23, 42)
let newAndOld = Observable.zip(values, values.skip(1)) { (previous: $0, current: $1) }
.subscribe(onNext: { pair in
print("current: \(pair.current) - previous: \(pair.previous)")
})
//current: 8 - previous: 4
//current: 15 - previous: 8
//current: 16 - previous: 15
//current: 23 - previous: 16
//current: 42 - previous: 23
Using protocols such as ExpressibleByStringLiteral
it is possible to provide an init
that will be automatically when a literal value is provided, allowing for nice and short syntax. This can be very helpful when writing mock or test data.
import Foundation
extension URL: ExpressibleByStringLiteral {
public init(stringLiteral value: String) {
self.init(string: value)!
}
}
let url: URL = "http://www.google.fr"
NSURLConnection.canHandle(URLRequest(url: "http://www.google.fr"))
Through some clever use of Swift private
visibility it is possible to define a container that holds any untrusted value (such as a user input) from which the only way to retrieve the value is by making it successfully pass a validation test.
import Foundation
struct Untrusted<T> {
private(set) var value: T
}
protocol Validator {
associatedtype T
static func validation(value: T) -> Bool
}
extension Validator {
static func validate(untrusted: Untrusted<T>) -> T? {
if self.validation(value: untrusted.value) {
return untrusted.value
} else {
return nil
}
}
}
struct FrenchPhoneNumberValidator: Validator {
static func validation(value: String) -> Bool {
return (value.count) == 10 && CharacterSet(charactersIn: value).isSubset(of: CharacterSet.decimalDigits)
}
}
let validInput = Untrusted(value: "0122334455")
let invalidInput = Untrusted(value: "0123")
FrenchPhoneNumberValidator.validate(untrusted: validInput) // returns "0122334455"
FrenchPhoneNumberValidator.validate(untrusted: invalidInput) // returns nil
With the addition of keypaths in Swift 4, it is now possible to easily implement the builder pattern, that allows the developer to clearly separate the code that initializes a value from the code that uses it, without the burden of defining a factory method.
import UIKit
protocol With {}
extension With where Self: AnyObject {
@discardableResult
func with<T>(_ property: ReferenceWritableKeyPath<Self, T>, setTo value: T) -> Self {
self[keyPath: property] = value
return self
}
}
extension UIView: With {}
let view = UIView()
let label = UILabel()
.with(\.textColor, setTo: .red)
.with(\.text, setTo: "Foo")
.with(\.textAlignment, setTo: .right)
.with(\.layer.cornerRadius, setTo: 5)
view.addSubview(label)
🚨 The Swift compiler does not perform OS availability checks on properties referenced by keypaths. Any attempt to use a KeyPath
for an unavailable property will result in a runtime crash.
I share the credit for this tip with Marion Curtil.
When a type stores values for the sole purpose of parametrizing its functions, it’s then possible to not store the values but directly the function, with no discernable difference at the call site.
import Foundation
struct MaxValidator {
let max: Int
let strictComparison: Bool
func isValid(_ value: Int) -> Bool {
return self.strictComparison ? value < self.max : value <= self.max
}
}
struct MaxValidator2 {
var isValid: (_ value: Int) -> Bool
init(max: Int, strictComparison: Bool) {
self.isValid = strictComparison ? { $0 < max } : { $0 <= max }
}
}
MaxValidator(max: 5, strictComparison: true).isValid(5) // false
MaxValidator2(max: 5, strictComparison: false).isValid(5) // true
Functions are first-class citizen types in Swift, so it is perfectly legal to define operators for them.
import Foundation
let firstRange = { (0...3).contains($0) }
let secondRange = { (5...6).contains($0) }
func ||(_ lhs: @escaping (Int) -> Bool, _ rhs: @escaping (Int) -> Bool) -> (Int) -> Bool {
return { value in
return lhs(value) || rhs(value)
}
}
(firstRange || secondRange)(2) // true
(firstRange || secondRange)(4) // false
(firstRange || secondRange)(6) // true
Typealiases are great to express function signatures in a more comprehensive manner, which then enables us to easily define functions that operate on them, resulting in a nice way to write and use some powerful API.
import Foundation
typealias RangeSet = (Int) -> Bool
func union(_ left: @escaping RangeSet, _ right: @escaping RangeSet) -> RangeSet {
return { left($0) || right($0) }
}
let firstRange = { (0...3).contains($0) }
let secondRange = { (5...6).contains($0) }
let unionRange = union(firstRange, secondRange)
unionRange(2) // true
unionRange(4) // false
By returning a closure that captures a local variable, it's possible to encapsulate a mutable state within a function.
import Foundation
func counterFactory() -> () -> Int {
var counter = 0
return {
counter += 1
return counter
}
}
let counter = counterFactory()
counter() // returns 1
counter() // returns 2
⚠️ Since Swift 4.2,
allCases
can now be synthesized at compile-time by simply conforming to the protocolCaseIterable
. The implementation below should no longer be used in production code.
Through some clever leveraging of how enums are stored in memory, it is possible to generate an array that contains all the possible cases of an enum. This can prove particularly useful when writing unit tests that consume random data.
import Foundation
enum MyEnum { case first; case second; case third; case fourth }
protocol EnumCollection: Hashable {
static var allCases: [Self] { get }
}
extension EnumCollection {
public static var allCases: [Self] {
var i = 0
return Array(AnyIterator {
let next = withUnsafePointer(to: &i) {
$0.withMemoryRebound(to: Self.self, capacity: 1) { $0.pointee }
}
if next.hashValue != i { return nil }
i += 1
return next
})
}
}
extension MyEnum: EnumCollection { }
MyEnum.allCases // [.first, .second, .third, .fourth]
The if-let syntax is a great way to deal with optional values in a safe manner, but at times it can prove to be just a little bit to cumbersome. In such cases, using the Optional.map()
function is a nice way to achieve a shorter code while retaining safeness and readability.
import UIKit
let date: Date? = Date() // or could be nil, doesn't matter
let formatter = DateFormatter()
let label = UILabel()
if let safeDate = date {
label.text = formatter.string(from: safeDate)
}
label.text = date.map { return formatter.string(from: $0) }
label.text = date.map(formatter.string(from:)) // even shorter, tough less readable
📣 NEW 📣 Swift Tips are now available on YouTube 👇
Summary
String
interpolationstructs
NSAttributedString
through a Function Builderswitch
and if
as expressionsguard
statementsinit
without loosing the compiler-generated oneenum
Never
to represent impossible code pathsDecodable
enum
[weak self]
and guard
userInfo
Dictionary
typealias
to its fullestforEach
reduce()
Optional
booleansSequence
nil
valuesmap()
Tips
Author: vincent-pradeilles
Source code: https://github.com/vincent-pradeilles/swift-tips
License: MIT license
#swift
1652837384
In this tutorial, you will learn how to build a single page application. I'll take you through the process step by step, using cutting edge technologies like Laravel 9, Jetstream, Vuejs, Inertiajs, MySQL, Tailwind CSS, and Docker.
Let's get started.
To follow along you will need:
This guide is organized into 10 chapters and is based off a live coding series that I record. The live coding series is completely unscripted, so there will be bugs and gotchas there that you won't find in this guide.
You can find the complete playlist at the end of this article.
Everything here should just work, but if it doesn't feel free to ask for help by joining my community on Slack. There you can share code snippets and chat with me directly.
Original article source at https://www.freecodecamp.org
First, let's go over the different tools we'll be using in this project.
Docker is a set of platform as a service products that use OS-level virtualization to deliver software in packages called containers.
To simplify this concept, Docker lets you package applications and dependencies in a container.
A containerized application allows you to have a flexible development environment so that you can run different applications without worrying about dependencies, their requirements, and conflicts between different versions. You can easily run applications that, for instance, require two different versions of PHP and MySQL.
Each team member can quickly reproduce the same environment of your application by simply running the same container's configuration.
If you want to learn more about Docker, its Documentation is a great place to start.
Here's a Handbook on Docker essentials, as well, so you can practice your skills.
MySQL is an open-source relational database management system. You can use it to organize data into one or more tables with data that may be related to each other.
We need to store data somewhere and here is where MySQL comes into play.
Here are the Docs if you want to read up more. Here's a full free course on MySQL if you want to dive deeper.
Laravel is a free, open-source PHP web framework that helps you develop web applications following the model–view–controller architectural pattern.
Laravel is an amazing PHP framework that you can use to create bespoke web applications.
Here's the Laravel Documentation for more info, and here's a full project-based course to help you learn Laravel.
Laravel Sail is a lightweight command-line interface for interacting with Laravel's default Docker development environment.
Sail provides a great starting point for building a Laravel application using PHP, MySQL, and Redis without requiring prior Docker experience.
Usually, creating a development environment to build such applications means you have to install software, languages, and frameworks on your local machine – and that is time-consuming. Thanks to Docker and Laravel Sail we will be up and running in no time!
Laravel Sail is supported on macOS, Linux, and Windows via WSL2.
Here's the Documentation if you want to read up on it.
When building web applications, you likely want to let users register and log in to use your app. That is why we will use Jetstream.
Laravel Jetstream is a beautifully designed application starter kit for Laravel and provides the perfect starting point for your next Laravel application.
It uses Laravel Fortify to implement all the back end authentication logic.
Here are the Docs.
Vue.js is an open-source model–view–ViewModel front end JavaScript framework for building user interfaces and single-page applications.
Vue is a fantastic framework that you can use as a stand-alone to build single-page applications, but you can also use it with Laravel to build something amazing.
Here's the Vue Documentation if you want to read up. And here's a great Vue course to get you started.
Inertia is the glue between Laravel and Vuejs that we will use to build modern single-page applications using classic server-side routing.
You can learn more about it in the Documentation here.
Tailwind CSS is a utility-first CSS framework packed with classes like flex, pt-4, text-center, and rotate-90 that you can use to build any design, directly in your markup
We'll use it in this project to build our design. Here's a quick guide to get you up and running if you aren't familiar with Tailwind.
To follow along with my live coding (and this tutorial), you will need to install Docker desktop on your machine. If you are using Windows, you will also need to enable WSL in your system settings.
Visit the Docker getting started page to install Docker Desktop.
If you are on Windows, enable WSL2 by following the steps here.
If you have any trouble, feel free to reach out or join my community on Slack to get help.
If you have successfully installed Docker Desktop on your machine, we can open the terminal and install Laravel 9.
Open a terminal window and browse to a folder where you want to keep your project. Then run the command below to download the latest Laravel files. The command will put all files inside a folder called my-example-app, which you can tweak as you like.
# Download laravel
curl -s "https://laravel.build/my-example-app" | bash
# Enter the laravel folder
cd my-example-app
sail up
commandWith Docker Desktop up and running, the next step is to start Laravel sail to build all the containers required to run our application locally.
Run the following command from the folder where all Laravel files have been downloaded:
vendor/bin/sail up
It will take a minute. Then visit http://localhost and you should see your Laravel application.
If you run sail up
and you get the following error, it is likely that you need to update Docker Desktop:
ERROR: Service 'laravel.test' failed to build:
In this section, we will define a basic roadmap, install Laravel 9 with Laravel Sail, Run sail, and build the containers.
I will also take you on a tour of Laravel Sail and the sail commands.
Then we will install Jetstream and scaffold Vue and Inertia files and have a look at the files and available features.
Next, we will populate our database and add the front end provided by Jetstream to register an account and log into a fresh Laravel application.
Finally, we will have a look at the Jetstream dashboard, and the Inertia/Vue Components and then start playing around.
Along the way, we'll disable the registration, enable the Jetstream user profile picture feature, and then add our first Inertia page where we'll render some data taken from the database.
Here's the live coding video if you want to follow along that way:
And if you prefer following along in this written tutorial, here are all the steps.
Just a reminder – you should have Laravel installed with Sail and have Docker set up on your machine. You can follow the steps above to do so if you haven't already.
With Laravel Sail installed, our usual Laravel commands have sligtly changed.
For instance, instead of running the Laravel artisan command using PHP like php artisan
, we now have to use Sail, like so: sail artisan
.
The sail artisan
command will return a list of all available Laravel commands.
Usually, when we work with Laravel, we also have to run the npm
and composer
commands.
Again, we need to prefix our commands with sail
to make them run inside the container.
Below you'll find a list of some commands you will likely have to run:
# Interact with the database - run the migrations
sail artisan migrate # It was: php artisan migrate
# Use composer commands
sail composer require <packageName> # it was: composer require <packageName>
# Use npm commands
sail npm run dev # it was: npm run dev
You can read more in the Sail documentation.
Let's now install the Laravel Jetstream authentication package and use the Inertia scaffolding with Vue3.
cd my-example-app
sail composer require laravel/jetstream
Remember to prefix the composer command with sail
.
The command above has added a new command to Laravel. Now we need to run it to install all the Jetstream components:
sail artisan jetstream:install inertia
Next we need to compile all static assets with npm:
sail npm install
sail npm run dev
Before we can actually see our application, we will need to run the database migrations so that the session table, required by Jetstream, is present.
sail artisan migrate
Done! Jetstream is now installed in our application. If you visit http://localhost
in your browser you should see the Laravel application with two links at the top to register and log in.
Before creating a new user, let's have a quick look at the database configuration that Laravel Sail has created for us in the .env
file.
DB_CONNECTION=mysql
DB_HOST=mysql
DB_PORT=3306
DB_DATABASE=my-example-app
DB_USERNAME=sail
DB_PASSWORD=password
As you can see, Laravel Sail configures everything we need to access the database container that is running on Docker. The DB_DATABASE
is the name of the database and it is the same as the project folder. This is why in the previous step we were able to run the migrate
command without issues.
Since we already migrated all database tables, we can now use the Laravel built-in user factory to create a new user then use its details to log in our user dashboard.
Let's open artisan tinker to interact with our application.
sail artisan tinker
The command above will open a command line interface that we can use to interact with our application. Let's create a new user.
User::factory()->create()
The command above will create a new user and save its data in our database. Then it will render the user data onto the screen. Make sure to copy the user email so we can use it later to log in. Then exit by typing exit;
.
The default password for every user created with a factory is password
.
Let's visit the login page and access our application dashboard.
After login you are redirected to the Jetstream dashboard, which looks amazing by default. We can customize it as we like, but it is just a starting point.
The first thing you may notice after installing Jetstram is that there are a number of Vue components registered in our application. Not only that, also Inertia brings in Vue components.
To use Inertia, we need to get familiar with it when defining routes.
When we installed Jetstream, it created inside the resources/js
directory a number of subfolders where all our Vue components live. There are not just simple components but also Pages components rendered by inertia as our Views.
The Jetstream inertia scaffolding created:
resources/js/Jetstream
Here we have 27 components used by Jetstream, but we can use them in our application too if we want.resources/js/Layouts
In this folder there is the layout component used by inertia to render the dashboard pageresources/js/Pages
This is where we will place all our Pages (views) components. You will find the Dashboard page as well as the Laravel Welcome page components here.The power of Inertia mostly comes from how it connects Vue and Laravel, letting us pass data (Database Models and more) as props to our Vue Pages components.
When you open the routes/web.php
file you will notice that we no longer return a view but instead we use Inertia
to render a Page component.
Let's examine the /
homepage route that renders the Welcome component.
Route::get('/', function () {
return Inertia::render('Welcome', [
'canLogin' => Route::has('login'),
'canRegister' => Route::has('register'),
'laravelVersion' => Application::VERSION,
'phpVersion' => PHP_VERSION,
]);
});
It looks like our usual Route definition, exept that in the closure we are returning an \Inertia\Response
by calling the render
method of the Inertia class Inertia::render()
.
This method accepts two parameters. The first is a component name. Here we passed the Welcome
Page component, while the second parameter is an associative array that will turn into a list of props
to pass to the component. Here is where the magic happens.
Looking inside the Welcome component, you will notice that in its script section, we simply define four props matching with the keys of our associative array. Then inertia will do the rest.
<script>
import { defineComponent } from 'vue'
import { Head, Link } from '@inertiajs/inertia-vue3';
export default defineComponent({
components: {
Head,
Link,
},
// 👇 Define the props
props: {
canLogin: Boolean,
canRegister: Boolean,
laravelVersion: String,
phpVersion: String,
}
})
</script>
We can then just call the props inside the template. If you look at the template section you will notice that laravelVersion
and phpVersion
are referenced in the code as you normally would do with props in Vuejs.
<div class="ml-4 text-center text-sm text-gray-500 sm:text-right sm:ml-0">
Laravel v{{ laravelVersion }} (PHP v{{ phpVersion }})
</div>
The dashboard component is a little different. In fact it uses the Layout defined under Layouts/AppLayout.vue
and uses the Welcome
component to render the Dashboard page content, which is the same as the laravel Welcome page.
<template>
<app-layout title="Dashboard">
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">
Dashboard
</h2>
</template>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
<welcome />
</div>
</div>
</div>
</app-layout>
</template>
Inside the layout component you will notice the two inertia components Head
and Link
.
We can use the Head
component to add head elements to our page, like meta tags, page title, and so on. The Link
component is a wrapper aroud a standard anchor tag that incercepts click events and prevents full page reload as you can read in the Inertia documentation.
If you are following along, the next step I'll take is to disable one on the features Jetstream provides – register an account.
To do that, we can navigate to config/fortify.php
and comment out line 135 Features::registration()
from the features array.
'features' => [
//Features::registration(),
Features::resetPasswords(),
// Features::emailVerification(),
Features::updateProfileInformation(),
Features::updatePasswords(),
Features::twoFactorAuthentication([
'confirmPassword' => true,
]),
],
If we visit the welcome page we will notice that the register
link is gone. Also, the route is no longer listed when we run sail artisan route:list
.
Now let's try to enable the Jetstream feature called ProfilePhotos. As you can guess, this will allow the user to add a profile picture.
To do that we need to visit config/jetstream.php
and uncomment line 59 Features::profilePhoto
.
'features' => [
// Features::termsAndPrivacyPolicy(),
Features::profilePhotos(), // 👈
// Features::api(),
// Features::teams(['invitations' => true]),
Features::accountDeletion(),
],
If you log in you will see that in the user profile, a new section is available to upload a profile picture.
But before doing anything else we need to run sail artisan storage:link
so that Laravel creates a symlink to the storage/app/public
folder where we will save all user profile images.
Now try to visit the user profile and update the profile picture. If you get a 404 on the image this is because by default Laravel sail assumes we are using Laravel valet and sets the app URL like so APP_URL=http://my-example-app.test
in the .env
file. Let's change it and use localhost instead.
APP_URL=http://localhost
Now we should be good to go and be able to see and change our profile image!🥳
Since we are rendering Vue components instead of blade views, it is wise to start sail npm run watch
to watch and recompile our Vue components as we create or edit them. Next let's add a new Photos page.
I will start by creating a new Route inside web.php:
Route::get('photos', function () {
//dd(Photo::all());
return Inertia::render('Guest/Photos');
});
In the code above I defined a new GET route and then rendered a component that I will place inside the resources/js/Pages/Guest
and call Photos
. Let's create it.
Create a Guest folder:
cd resources/js/Pages
mkdir Guest
cd Guest
touch Photos.vue
Then let's define a basic component:
<template>
<h1>Photos Page</h1>
</template>
If we visit http://localhost/photos/
we will see our new page, cool! Let's copy over the page structure from the Welcome page so that we get the login and dashboard links as well.
The component will change to this:
<template>
<Head title="Phots" />
<div class="relative flex items-top justify-center min-h-screen bg-gray-100 dark:bg-gray-900 sm:items-center sm:pt-0">
<div v-if="canLogin" class="hidden fixed top-0 right-0 px-6 py-4 sm:block">
<Link v-if="$page.props.user" :href="route('admin.dashboard')" class="text-sm text-gray-700 underline">
Dashboard
</Link>
<template v-else>
<Link :href="route('login')" class="text-sm text-gray-700 underline">
Log in
</Link>
<Link v-if="canRegister" :href="route('register')" class="ml-4 text-sm text-gray-700 underline">
Register
</Link>
</template>
</div>
<div class="max-w-6xl mx-auto sm:px-6 lg:px-8">
<h1>Photos</h1>
</div>
</div>
</template>
<script>
import { defineComponent } from 'vue'
import { Head, Link } from '@inertiajs/inertia-vue3';
export default defineComponent({
components: {
Head,
Link,
},
props: {
canLogin: Boolean,
canRegister: Boolean,
}
})
</script>
The next step is to render a bunch of data onto this new page. For that we will build a Model and add some records to the database.
saild artisan make:model Photo -mfcr
This command creates a Model called Photo
, plus a database migration table class, a factory, and a resource controller.
Now let's define the database table inside the migration we just creted. Visit the database/migrations
folder and you should see a file with a name similar to this: 2022_02_13_215119_create_photos_table
(yours will be sligly different).
Inside the migration file we can define a basic table like the following:
public function up()
{
Schema::create('photos', function (Blueprint $table) {
$table->id();
$table->string('path');
$table->text('description');
$table->timestamps();
});
}
For our table we defined just two new columns, path
and description
, plus the id
, created_at
and updated_at
that will be created by the $table->id()
and by the $table->timestamps()
methods.
After the migration we will define a seeder and then run the migrations and seed the database.
At the top of the database/seeders/PhotoSeeder.php
file we will import our Model and Faker:
use App\Models\Photo;
use Faker\Generator as Faker;
Next we will implement the run method using a for loop to create 10 records in the database.
public function run(Faker $faker)
{
for ($i = 0; $i < 10; $i++) {
$photo = new Photo();
$photo->path = $faker->imageUrl();
$photo->description = $faker->paragraphs(2, true);
$photo->save();
}
}
We are ready to run the migrations and seed the database.
sail artisan migrate
sail artisan db:seed --class PhotoSeeder
We are now ready to show the data on the Guest/Photos
page component.
First update the route and pass a collection of Photos as props to the rendered component:
Route::get('photos', function () {
//dd(Photo::all());
return Inertia::render('Guest/Photos', [
'photos' => Photo::all(), ## 👈 Pass a collection of photos, the key will become our prop in the component
'canLogin' => Route::has('login'),
'canRegister' => Route::has('register'),
]);
});
Second, pass the prop to the props in the script section of the Guest/Photos component:
props: {
canLogin: Boolean,
canRegister: Boolean,
photos: Array // 👈 Here
}
Finally loop over the array and render all photos in the template section, just under the h1:
<section class="photos">
<div v-for="photo in photos" :key="photo.id" class="card" >
<img :src="photo.path" alt="">
</div>
</section>
Done! if you visit the /photos
page you should see ten photos. 🥳
In this chapter we will Re-route the Jetstream dashboard and make a route group for all admin pages.
Then we will see how to add a new link to the dashboard and add a new admin page.
Finally we will take a collection of data from the db and render them in a basic table. The default table isn't cool enough, so for those reading this article, I decided to add a Tailwind table component.
If we look at the config/fortify.php
file we can see that around line 64 there is a key called home. It is calling the Home
constant of the Route service provider.
This means that we can tweek the constant and redirect the authenticated user to a different route.
Lets go through it step-by-step:
admin/
instead of '/dashboard'Our application will have only a single user, so once they're logged in it is clearly the site admin – so makes sense to redirect to an admin
URI.
Change the HOME constant in app/Providers/RouteServiceProvider.php
around line 20 to match the following:
public const HOME = '/admin';
Next let's update our route inside web.php. We will change the route registered by Jetstream from this:
Route::middleware(['auth:sanctum', 'verified'])->get('/', function () {
return Inertia::render('Dashboard');
})->name('dashboard');
To this:
Route::middleware(['auth:sanctum', 'verified'])->prefix('admin')->name('admin.')->group(function () {
Route::get('/', function () {
return Inertia::render('Dashboard');
})->name('dashboard');
// other admin routes here
});
The route above is a route group that uses the auth:sanctum
middleware for all routes within the group, a prefix of admin
, and adds a admin
suffix to each route name.
The end result is that we will be able to refer to the dashboard route by name, which now will be admin.dashboard
. When we log in, we will be redirected to the admin
route. Our dashboard route will respond since it's URI is just /
but the goup prefix will prefix every route in the group and make their URI start with admin
.
If you now run sail artisan route:list
you will notice that the dashboard route has changed as we expected.
Before moving to the next step we need to update both the /layouts/AppLayout.vue
and /Pages/Welcome.vue
components.
Do you remeber that the dashboard route name is now admin.dashboard
and not just dashboard
?
Let's inspect the two components and update every reference of route('dahsboard')
to this:
route('admin.dahsboard')
and also every reference of route().current('dashboard')
to this:
route().current('admin.dashboard')
After all the changes, make sure to recompile the Vue components and watch changes by running sail npm run watch
. Then visit the home page to check if everything is working.
Now, to add a new admin page where we can list all photos stored in the database, we need to add a new route to the group we created earlier. Let's hit the web.php
file and make our changes.
In the Route group we will add a new route:
Route::middleware(['auth:sanctum', 'verified'])->prefix('admin')->name('admin.')->group(function () {
Route::get('/', function () {
return Inertia::render('Dashboard');
})->name('dashboard');
// 👇 other admin routes here 👇
Route::get('/photos', function () {
return inertia('Admin/Photos');
})->name('photos'); // This will respond to requests for admin/photos and have a name of admin.photos
});
In the new route above we used the inertia()
helper function that does the same exact thing – returns an Inertia/Response and renders our Page component. We placed the component under an Admin
folder inside Pages
and we will call it Photos.vue
.
Before we create the component, let's add a new link to the dashboard that points to our new route.
Inside AppLayout.vue
, find the Navigation Links
comment and copy/paste the jet-nav-link
component that is actually displaing a link to the dashboard and make it point to our new route.
You will end up having something like this:
<!-- Navigation Links -->
<div class="hidden space-x-8 sm:-my-px sm:ml-10 sm:flex">
<jet-nav-link :href="route('admin.dashboard')" :active="route().current('admin.dashboard')">
Dashboard
</jet-nav-link>
<!-- 👇 here it is our new link -->
<jet-nav-link :href="route('admin.photos')" :active="route().current('admin.photos')">
Photos
</jet-nav-link>
</div>
Our link above uses route('admin.photos')
to point to the correct route in the admin group.
If you visit localhost/dashboard
and open the inspector, you should see an error:
Error: Cannot find module `./Photos.vue`
It is fine – we haven't created the Photos page component yet. So let's do it now!
Make a file named Photos.vue
inside the Pages/Admin
folder. Below are the bash commands to create the folder and the file via terminal, but you can do the same using your IDE's graphical interface.
cd resources/js/Pages
mkdir Admin
touch Admin/Photos.vue
To make this new page look like the Dashboard page, we will copy over its content. You should end up having something like this:
<template>
<app-layout title="Dashboard"> <!-- 👈 if you want you can update the page title -->
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">Photos</h2>
</template>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-xl sm:rounded-lg">
<!-- 👇 All photos for the Admin page down here -->
<h1 class="text-2xl">Photos</h1>
</div>
</div>
</div>
</app-layout>
</template>
<script>
import { defineComponent } from "vue";
import AppLayout from "@/Layouts/AppLayout.vue";
export default defineComponent({
components: {
AppLayout,
},
});
</script>
I removed a few pieces from the Dashboard template so make sure to double check the code above. The welcome
component was removed from the template as it is not required in this page, and also its reference in the script section. The rest is identical.
Feel free to update the page title referenced as prop on the <app-layout title="Dashboard">
.
Now when you visit localhost/admin
you can click on the Photos menu item and see our Photos page component content. It's not much for now, just an h1
.
Now it's time to render the data onto a table. To make things work let's first add our markup and fake that we already have access to as an array of objects and loop over them inside our table. Than we will figure out how to make things work for real.
<table class="table-auto w-full text-left">
<thead>
<tr>
<th>ID</th>
<th>Photo</th>
<th>Desciption</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<tr v-for="photo in photos">
<td>{{ photo.id }}</td>
<td><img width="60" :src="photo.path" alt="" /></td>
<td>{{photo.description}}</td>
<td>View - Edit - Delete</td>
</tr>
</tbody>
</table>
Ok, since we assumed that our component has access to a list of Photos, let's pass a new prop to the component from the Route.
Update the route in web.php and pass to the inertia()
function a second argument that will be an associative array. It will have its keys passed as props to the Vue Page component.
In it we will call Photo::all()
to have a collection to assign to a photos
key, but you can use other eloquent methods if you want to paginate the results, for example.
Route::get('/photos', function () {
return inertia('Admin/Photos', [
'photos' => Photo::all()
]);
})->name('photos');
To connect the prop to our Page component we need to define the prop also inside the component.
<script>
import { defineComponent } from "vue";
import AppLayout from "@/Layouts/AppLayout.vue";
export default defineComponent({
components: {
AppLayout,
},
/* 👇 Pass the photos array as a props 👇 */
props: {
photos: Array,
},
});
</script>
Tailwind is a CSS framework similar to Bootstrap. There are a number of free to use components that we can grab from the documentation, tweak, and use.
This table component is free and looks nice:https://tailwindui.com/components/application-ui/lists/tables.
We can tweek the Photos page template and use the Tailwind table component to get a nice looking table like so:
<template>
<app-layout title="Dashboard">
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">Photos</h2>
</template>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<!-- All posts goes here -->
<h1 class="text-2xl">Photos</h1>
<a class="px-4 bg-sky-900 text-white rounded-md" href>Create</a>
<div class="flex flex-col">
<div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
<div class="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
<div class="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th
scope="col"
class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>ID</th>
<th
scope="col"
class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>Photos</th>
<th
scope="col"
class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>Description</th>
<th scope="col" class="relative px-6 py-3">
<span class="sr-only">Edit</span>
</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr v-for="photo in photos" :key="photo.id">
<td class="px-6 py-4 whitespace-nowrap">
<div
class="text-sm text-gray-900"
>{{ photo.id }}</div>
</td>
<td class="px-6 py-4 whitespace-nowrap">
<div class="flex items-center">
<div class="flex-shrink-0 h-10 w-10">
<img
class="h-10 w-10 rounded-full"
:src="photo.path"
alt
/>
</div>
</div>
</td>
<td class="px-6 py-4 whitespace-nowrap">
<div class="text-sm text-gray-900">
{{ photo.description.slice(0, 100) + '...' }}
</div>
</td>
<!-- ACTIONS -->
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<a href="#" class="text-indigo-600 hover:text-indigo-900">
View - Edit - Delete
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</app-layout>
</template>
For the next section we will look into how to submit a form so that we can add a new photo to the database.
Add a link that points to a create route:
<a class="px-4 bg-sky-900 text-white rounded-md" :href="route('admin.photos.create')">Create</a>
Create the route within the admin group:
Route::get('/photos/create', function () {
return inertia('Admin/PhotosCreate');
})->name('photos.create');
Let's add also the route that will handle the form submission for later:
Route::post('/photos', function () {
dd('I will handle the form submission')
})->name('photos.store');
Create the Admin/PhotosCreate.vue
component:
<template>
<app-layout title="Dashboard">
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">Photos</h2>
</template>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<h1 class="text-2xl">Add a new Photo</h1>
<!-- 👇 Photo creation form goes here -->
</div>
</div>
</app-layout>
</template>
<script>
import { defineComponent } from "vue";
import AppLayout from "@/Layouts/AppLayout.vue";
export default defineComponent({
components: {
AppLayout,
},
});
</script>
The next step is to add the form to the page and figure out how to submit it.
If you hit the Inertia documentation you will find out that there is a useForm class that we can use to simplify the process.
First, import the module inside the script tag of the Admin/PhotosCreate.vue component:
import { useForm } from '@inertiajs/inertia-vue3';
Next we can use it in the setup function (Vue 3 composition API):
setup () {
const form = useForm({
path: null,
description: null,
})
return { form }
}
In the code above we defined the function called setup()
then a constant called form
to have the useForm()
class assigned to it.
Inside its parentheses we defined two properties, path
and description
which are the column names of our photos model.
Finally we returned the form
variable for the setup function. This is to make the variable available inside our template.
Next we can add the form markup:
<form @submit.prevent="form.post(route('admin.photos.store'))">
<div>
<label for="description" class="block text-sm font-medium text-gray-700"> Description </label>
<div class="mt-1">
<textarea id="description" name="description" rows="3" class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 mt-1 block w-full sm:text-sm border border-gray-300 rounded-md" placeholder="lorem ipsum" v-model="form.description"/>
</div>
<p class="mt-2 text-sm text-gray-500">Brief description for your photo</p>
<div class="text-red-500" v-if="form.errors.description">{{form.errors.description}}</div>
</div>
<div>
<label class="block text-sm font-medium text-gray-700"> Photo </label>
<div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md">
<div class="space-y-1 text-center">
<svg class="mx-auto h-12 w-12 text-gray-400" stroke="currentColor" fill="none" viewBox="0 0 48 48" aria-hidden="true">
<path d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" />
</svg>
<div class="flex text-sm text-gray-600">
<label for="path" class="relative cursor-pointer bg-white rounded-md font-medium text-indigo-600 hover:text-indigo-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-indigo-500">
<span>Upload a file</span>
<input id="path" name="path" type="file" class="sr-only" @input="form.path = $event.target.files[0]" />
</label>
<p class="pl-1">or drag and drop</p>
</div>
<p class="text-xs text-gray-500">PNG, JPG, GIF up to 10MB</p>
</div>
</div>
</div>
<div class="text-red-500" v-if="form.errors.path">{{form.errors.path}}</div>
<button type="submit" :disabled="form.processing" class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500">Save</button>
</form>
The code above uses the Vue v-on directive short end syntax @submit.prevent="form.post(route('admin.photos.store'))"
on the form tag, and the dom event submit
with the prevent
modifier.
Then it uses the form
variable that we created earlier and a post
method. This is available because we are using the useForm
class.
Next we point the form to the route named admin.photos.store that we created earlier.
Inside the form we have two groups of inputs. First, we have the textarea that uses the v-model to bind it to the property form.description
that we declared before.
The second group uses the form.path
in a Tailwind component (showing the markup for a drop file area).
Right now we are allowing users to upload only a single photo using the v-on directive on the input DOM event @input="form.path = $event.target.files[0]"
.
The last two things to notice are the error handling done via <div class="text-red-500" v-if="form.errors.path">{{form.errors.path}}</div>
for the path and also for the description.
Finally we use form.processing
to disable the submit button while the form is processing.
The next step is to define the logic to save the data inside the database.
To store the data, we can edit the route we defined earlier like so:
Route::post('/photos', function (Request $request) {
//dd('I will handle the form submission')
//dd(Request::all());
$validated_data = $request->validate([
'path' => ['required', 'image', 'max:2500'],
'description' => ['required']
]);
//dd($validated_data);
$path = Storage::disk('public')->put('photos', $request->file('path'));
$validated_data['path'] = $path;
//dd($validated_data);
Photo::create($validated_data);
return to_route('admin.photos');
})->name('photos.store');
The code above uses dependency injection to allow us to use the parameter $request
inside the callback function.
We first validate the request and save the resulting array inside the variable $validated_data
. Then we use the Storage
facades to save the file in the filesystem and obtain the file path that we store inside the $path variable
.
Finally we add a path
key to the associative array and pass to it the $path
variable. Next we create the resource in the database using the Photo::create
method and redirect the user to the admin.photos
page using the new to_route()
helper function.
Make sure to import the Request
class and the Storage
facades at the top of the web.php file like so:
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
Now we can add a new photo in the database and show a list of photos for both the admin and standard visitors.
Next we need to complete the CRUD operations and allow the user to edit/update a photo and delete it.
Let's start by adding the routes responsible for showing the forms used to edit the resource and update its values onto the database.
Just under the other routes in the Admin group, let's add the following code:
Route::get('/photos/{photo}/edit', function(Photo $photo){
return inertia('Admin/PhotosEdit', [
'photo' => $photo
]);
})->name('photos.edit');
The route above uses dependency injection to inject inside the function the current post, selected by the URI /photos/{photo}/edit
.
Next it returns the Inertia response via the inertia()
function that accepts the Component name 'Admin/PhotosEdit'
as its first parameter and an associative array as its second.
Doing ['photo' => $photo]
will allow us to pass the $photo
model as a prop to the component later.
Next let's add the new Page component under resources/js/Pages/Admin/PhotosEdit.vue
This will be its template:
<template>
<app-layout title="Edit Photo">
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">Edit Photo</h2>
</template>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<form @submit.prevent="form.post(route('admin.photos.update', photo.id))">
<div>
<label
for="description"
class="block text-sm font-medium text-gray-700"
>Description</label>
<div class="mt-1">
<textarea
id="description"
name="description"
rows="3"
class="shadow-sm focus:ring-indigo-500 focus:border-indigo-500 mt-1 block w-full sm:text-sm border border-gray-300 rounded-md"
placeholder="lorem ipsum"
v-model="form.description"
/>
</div>
<p class="mt-2 text-sm text-gray-500">Brief description for your photo</p>
<div
class="text-red-500"
v-if="form.errors.description"
>{{ form.errors.description }}</div>
</div>
<div class="grid grid-cols-2">
<div class="preview p-4">
<img :src="'/storage/' + photo.path" alt />
</div>
<div>
<label class="block text-sm font-medium text-gray-700">Photo</label>
<div
class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-md"
>
<div class="space-y-1 text-center">
<svg
class="mx-auto h-12 w-12 text-gray-400"
stroke="currentColor"
fill="none"
viewBox="0 0 48 48"
aria-hidden="true"
>
<path
d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
/>
</svg>
<div class="flex text-sm text-gray-600">
<label
for="path"
class="relative cursor-pointer bg-white rounded-md font-medium text-indigo-600 hover:text-indigo-500 focus-within:outline-none focus-within:ring-2 focus-within:ring-offset-2 focus-within:ring-indigo-500"
>
<span>Upload a file</span>
<input
id="path"
name="path"
type="file"
class="sr-only"
@input="form.path = $event.target.files[0]"
/>
</label>
<p class="pl-1">or drag and drop</p>
</div>
<p class="text-xs text-gray-500">PNG, JPG, GIF up to 10MB</p>
</div>
</div>
<div class="text-red-500" v-if="form.errors.path">{{ form.errors.path }}</div>
</div>
</div>
<button
type="submit"
:disabled="form.processing"
class="inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-md text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
>Update</button>
</form>
</div>
</div>
</app-layout>
</template>
The template is actually identical to the Create component, except for a few things. The form points to a route that expects a paramenter that we pass as the second argument to the funtion route
. It looks like this: <form @submit.prevent="form.post(route('admin.photos.update', photo.id))">
.
There is a section where we can see the original photo next to the upload form group:
<div class="preview p-4">
<img :src="'/storage/' + photo.path" alt />
</div>
The rest is identical, and here we have the script section:
import { defineComponent } from "vue";
import AppLayout from "@/Layouts/AppLayout.vue";
import { useForm } from '@inertiajs/inertia-vue3';
export default defineComponent({
components: {
AppLayout,
},
props: {
photo: Object
},
setup(props) {
const form = useForm({
_method: "PUT",
path: null,
description: props.photo.description,
})
return { form }
},
});
Notice that we are passing a props object with the photo key, which allows us to reference the model in the template.
Next, this _method: "PUT",
line of code is required to be able to submit a PUT
request instead of the POST
request called on the form tag.
Now let's implement the logic to handle the form submission inside the Route below.
In web.php just under the previous route, let's add one that responds to the PUT request submitted by our form.
Route::put('/photos/{photo}', function (Request $request, Photo $photo)
{
//dd(Request::all());
$validated_data = $request->validate([
'description' => ['required']
]);
if ($request->hasFile('path')) {
$validated_data['path'] = $request->validate([
'path' => ['required', 'image', 'max:1500'],
]);
// Grab the old image and delete it
// dd($validated_data, $photo->path);
$oldImage = $photo->path;
Storage::delete($oldImage);
$path = Storage::disk('public')->put('photos', $request->file('path'));
$validated_data['path'] = $path;
}
//dd($validated_data);
$photo->update($validated_data);
return to_route('admin.photos');
})->name('photos.update');
The route logic is straigthforward. First we validate the description, next we check if a file was uploaded and if so we validate it.
Then we delete the previously uploaded image Storage::delete($oldImage);
before storing the new image onto the datadabse and update the resource using $photo->update($validated_data);
.
As before with the store route, we redirect to the admin.photos
route using return to_route('admin.photos');
.
The last step we need to take is to write the logic to delete the photo. Let's start by adding the route.
Right below the previous route we can write:
Route::delete('/photos/{photo}', function (Photo $photo)
{
Storage::delete($photo->path);
$photo->delete();
return to_route('admin.photos');
})->name('photos.delete');
This route is also using a wildcard in its URI to identify the resource. Next, its second paramenter is the callback that uses the dependency injection as before. Inside the callback we first delete the image from the filesystem using Storage::delete($photo->path);
.
Then we remove the resource from the database $photo->delete();
and redirect the user back return to_route('admin.photos');
like we did in the previous reoute.
Now we need to add a delete button to the table we created in one of the previous steps to show all photos.
Inside the template section of the component Admin/Photos.vue
within the v-for
, we can add this Jetstream button:
<jet-danger-button @click="delete_photo(photo)">
Delete
</jet-danger-button>
Find the table cell that has the ACTIONS
comment and replace the DELETE
text with the button above.
So the final code will be:
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<a href="#" class="text-indigo-600 hover:text-indigo-900">
View - Edit -
<jet-danger-button @click="delete_photo(photo)">
Delete
</jet-danger-button>
</a>
</td>
As you can see there is a @click
event listener on the button. It calls a method delete_photo(photo)
that we need to define along with a bunch of other methods to have a nice modal opening to ask for confirmation from the user.
First import the Inertia helper function useForm:
// 0. Import the useForm class at the top of the script section along with all required components
import { useForm } from '@inertiajs/inertia-vue3';
import JetDangerButton from '@/Jetstream/DangerButton.vue'
import { ref } from "vue";
Remember to register the component JetDangerButton
inside the components object before moving forward.
Next add the setup()
function in the script section and implement the logic required to submit the form and show a modal. The comments in the code will guide you thorought all the steps.
// 1. add the setup function
setup() {
// 2. declare a form variable and assign to it the Inertia useForm() helper function
const form = useForm({
// 3. override the form method to make a DELETE request
_method: "DELETE",
});
// 4. define a reactive object with show_modal and photo property
// this will be used to figure out when to show the modal and the selected post values
const data = ref({
show_modal: false,
photo: {
id: null,
path: null,
description: null,
}
})
// 5. define the delete_photo function and update the values of the show_modal and photo properties
// of the reactive object defined above. This method is called by the delete button and will record the details
// of the selected post
const delete_photo = (photo) => {
//console.log(photo);
//console.log(photo.id, photo.path, photo.description);
data.value = {
photo: {
id: photo.id,
path: photo.path,
description: photo.description
},
show_modal: true
};
}
// 6. define the method that will be called when our delete form is submitted
// the form will be created next
const deleting_photo = (id) => {
form.post(route('admin.photos.delete', id))
closeModal();
}
// 7. delare a method to close the modal by setting the show_modal to false
const closeModal = () => {
data.value.show_modal = false;
}
// 8. remember to return from the setup function the all variables and methods that you want to expose
// to the template.
return { form, data, closeModal, delete_photo, deleting_photo }
}
Finally outside the v-for
loop add the modal using the following code. You can place this where you want but not inside the loop.
<JetDialogModal :show="data.show_modal">
<template #title>
Photo {{ data.photo.description.slice(0, 20) + '...' }}
</template>
<template #content>
Are you sure you want to delete this photo?
</template>
<template #footer>
<button @click="closeModal" class="px-4 py-2">Close</button>
<form @submit.prevent="deleting_photo(data.photo.id)">
<jet-danger-button type="submit">Yes, I am sure!</jet-danger-button>
</form>
</template>
</JetDialogModal>
This is our final JavaScript code:
import { defineComponent } from "vue";
import AppLayout from "@/Layouts/AppLayout.vue";
import TableComponent from "@/Components/TableComponent.vue";
import { Link } from '@inertiajs/inertia-vue3';
import { useForm } from '@inertiajs/inertia-vue3';
import JetDialogModal from '@/Jetstream/DialogModal.vue';
import JetDangerButton from '@/Jetstream/DangerButton.vue'
import { ref } from "vue";
export default defineComponent({
components: {
AppLayout,
Link,
TableComponent,
JetDialogModal,
JetDangerButton
},
props: {
photos: Array,
},
setup() {
const form = useForm({
_method: "DELETE",
});
const data = ref({
show_modal: false,
photo: {
id: null,
path: null,
description: null,
}
})
const delete_photo = (photo) => {
//console.log(photo);
console.log(photo.id, photo.path, photo.description);
data.value = {
photo: {
id: photo.id,
path: photo.path,
description: photo.description
},
show_modal: true
};
}
const deleting_photo = (id) => {
form.post(route('admin.photos.delete', id))
closeModal();
}
const closeModal = () => {
data.value.show_modal = false;
}
return { form, data, closeModal, delete_photo, deleting_photo }
}
});
</script>
And here we have the HTML:
<template>
<app-layout title="Dashboard">
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">Photos</h2>
</template>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<!-- All posts goes here -->
<h1 class="text-2xl">Photos</h1>
<a class="px-4 bg-sky-900 text-white rounded-md" href>Create</a>
<div class="flex flex-col">
<div class="-my-2 overflow-x-auto sm:-mx-6 lg:-mx-8">
<div class="py-2 align-middle inline-block min-w-full sm:px-6 lg:px-8">
<div class="shadow overflow-hidden border-b border-gray-200 sm:rounded-lg">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th
scope="col"
class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>ID</th>
<th
scope="col"
class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>Photos</th>
<th
scope="col"
class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider"
>Description</th>
<th scope="col" class="relative px-6 py-3">
<span class="sr-only">Edit</span>
</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
<tr v-for="photo in photos" :key="photo.id">
<td class="px-6 py-4 whitespace-nowrap">
<div
class="text-sm text-gray-900"
>{{ photo.id }}</div>
</td>
<td class="px-6 py-4 whitespace-nowrap">
<div class="flex items-center">
<div class="flex-shrink-0 h-10 w-10">
<img
class="h-10 w-10 rounded-full"
:src="photo.path"
alt
/>
</div>
</div>
</td>
<td class="px-6 py-4 whitespace-nowrap">
<div class="text-sm text-gray-900">
{{ photo.description.slice(0, 100) + '...' }}
</div>
</td>
<!-- ACTIONS -->
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<a href="#" class="text-indigo-600 hover:text-indigo-900">
View - Edit -
<jet-danger-button @click="delete_photo(photo)">
Delete
</jet-danger-button>
</a>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
<JetDialogModal :show="data.show_modal">
<template #title>
Photo {{ data.photo.description.slice(0, 20) + '...' }}
</template>
<template #content>
Are you sure you want to delete this photo?
</template>
<template #footer>
<button @click="closeModal" class="px-4 py-2">Close</button>
<form @submit.prevent="deleting_photo(data.photo.id)">
<jet-danger-button type="submit">Yes, I am sure!</jet-danger-button>
</form>
</template>
</JetDialogModal>
</app-layout>
</template>
That's it. If you did everything correctly you should be able to see all photos, create new photos as well as edit and delete them.
I will leave you some home work. Can you figure out how to implement the view and edit links before the delete button in the section below?
<!-- ACTIONS -->
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<a href="#" class="text-indigo-600 hover:text-indigo-900">
View - Edit -
<jet-danger-button @click="delete_photo(photo)">
Delete
</jet-danger-button>
</a>
</td>
During this guide we took our first steps and learned how to build a single page application using Laravel as our backend framework and Vue3 for the front end. We glued them together with Inertia js and built a simple photo application that lets a user manage photos.
We are just at the beginning of a fantastic journey. Learning new technologies isn't easy, but thanks to their exaustive documentations we can keep up and build awesome applications.
Your next step to master Laravel, Vue3, Inertia and all the tech we have been using so far is to hit their documentation and keep learning. Use the app we have build if you want, and improve it or start over from scratch.
This is just an overview of how I'd build a single page application using these technologies.
If you are familiar with server-side routing and Vuejs then you will enjoy bulding a single page application with Laravel, Inertia, and Vuejs. The learning curve isn't that steep plus you have great documentation to help you out.
You can find the source code for this guide here.
#laravel #laravel9 #jetstream #vuejs #inertiajs #mysql #tailwindcss #docker
1649473200
!important
in CSS is a special notation that we can apply to a CSS declaration to override other conflicting rules for the matching selector.
When we work on web projects, it is natural that we have some style declarations that other styles overrule.
This is not an issue for an experienced developer who understands the core mechanism of CSS. However, it can be difficult for beginners to understand why the style declarations they expect are not applied by the browser.
So, instead of them focusing on resolving the issue naturally, they tend to go for the quick fix by adding the !important
declaration to enforce the style they expect. While this approach might work for that moment, it can also initiate another complex problem.
In this guide, we will review the following, including how to use !important
and when we should use it:
!important
declaration before we use it:is()
and other related pseudo-class functions!important
declaration?Enough said, let’s dive in.
Understanding the core principles of CSS will naturally enable us to know when it’s obvious to use the !important
declaration. In this section, we will walk through some of these mechanisms.
Consider the HTML and CSS code below, what color do you think the heading text will be?
First, the HTML:
<h2 class="mytitle">This is heading text</h2>
Then, the CSS:
h2 {
color: blue;
}
h2 {
color: green;
}
The text will render green! This is basic CSS fundamental. With the CSS cascade algorithm, the ordering of CSS rules matters. In this case, the declaration that comes last in the source code wins.
Normally, this is logical. In the first place, we should not repeat the same selector as we did above. CSS does not want repetition, so it uses the last declaration rule.
However, there are cases whereby we create generic styles for the root elements, like the h2
, and then add classes to style specific elements. Let’s consider the following example as well, starting with the HTML:
<h2>This is heading text</h2>
<h2 class="mytitle">This is heading text</h2>
Then, let’s see the CSS:
.mytitle {
color: blue;
}
h2 {
color: green;
}
In the above code, the first h2
element has no class applied, so it is obvious that it gets the green color of the h2
selector.
However, the second h2
element uses the rule for the class selector, .mytitle
, even when the element selector rule comes last in the CSS code. The reason for that is that the class selector has a higher specificity when compared to the element selector.
In other words, the weight applied to the declaration in a class selector is more than element selector’s weight.
Similarly, the declaration in an ID selector is more than that of the class selector. In this case, the red color in the code below takes precedence:
<h2 id="maintitle" class="mytitle">This is heading text</h2>
Followed by the CSS:
.mytitle {
color: blue;
}
#maintitle {
color: red;
}
h2 {
color: green;
}
Furthermore, an inline style
attribute takes precedence over the ID selector, starting with the HTML:
<h2 id="maintitle" style="color: black;" class="mytitle">This is heading text</h2>
Then followed by the CSS:
.mytitle {/*...*/}
#maintitle {/*...*/}
h2 {/*...*/}
This is the ideal priority flow in CSS and must be maintained to avoid anomalies. The !important
declaration most of the time comes when we are oblivious of these basic rules.
The inline style attribute and each of the selectors have values that browsers assign to them. That way, it knows which one has higher or lower priority. Think of this value as a number of four single digits with the style
attribute assigned the strongest weight value of 1000
.
This follows the ID with a value of 0100
, then class with 0010
, and finally the element selector with 0001
.
Sometimes we can combine selectors targeting specific elements, as seen in the example below:
<h2 id="maintitle" class="mytitle">This is heading text</h2>
Followed by the CSS:
h2.mytitle {
color: blue;
}
#maintitle {
color: red;
}
h2 {
color: green;
}
The specificity of the h2.mytitle
selector in the CSS above is the addition of h2
and .mytitle
. That is, 0001 + 0010 = 0011
. This total value, however, is less than that of the #maintitle
ID that is 0100
.
So, the browser uses the declaration in the ID selector to override other conflicting rules. In a case of equal weight, the last rule declaration wins.
Now that we know which rules are most relevant and why the browser applies them, it will become naturally obvious whether or not to use this !important
declaration.
!important
declaration before we use itBefore we consider using the !important
notation, we must ensure that we follow the specificity rule and use the CSS cascade.
In the code below, we have the h2
and h3
elements styled to be a red
color:
<h2 class="mytitle">This is heading II text</h2>
<h3 class="mytitle">This is heading III text</h3>
Then, .mytitle
in CSS:
.mytitle {
color: red;
}
But, let’s say at some point, we want to give the h3
element a blue
color. Adding a style rule like the one below would not change the color because the class has more weight and it’s more specific than the element selector, as we’ve learned:
.mytitle {...}
h3 {
color: blue;
}
However, using the !important
on the lesser weight makes the browser enforce that declaration over other conflicting rules:
.mytitle {...}
h3 {
color: blue !important;
}
This is because the !important
notation increases the weight of the declaration in the cascade order of precedence. What this means is that we’ve disrupted the normal priority flow. Hence, bad practice, and can lead to difficulties in code maintenance and debugging.
If at some other point, we want to override the above important rule, we can apply another !important
notation on a declaration with higher specificity (or the same if it is lower down in the source). It can then lead to something like this:
h3 {
color: blue !important;
}
/* several lines of rules */
.mytitle {
color: green !important;
}
This is bad and should be avoided. Instead, we should check if:
Well, let’s find out. Back to our style rules, we can enforce a blue
color on the h3
element by increasing the specificity score.
As seen below, we can combine selectors until their specificity score supersedes the conflicting rule. The h3.mytitle
selector gives a specificity score of 0011
, which is more than the .mytitle
of 0010
score:
.mytitle {...}
h3.mytitle {
color: blue;
}
As we can see, instead of using the !important
declaration to enforce a rule, we focus on increasing the specificity score.
:is()
and other related pseudo-class functionsSometimes, we may trace issues to a pseudo-class function. So, knowing how it works can save us a lot of stress. Let’s see another example.
Imagine we are working on a project and see the following code:
<h1 id="header">
heading <span>span it</span>
<a href="#">link it</a>
</h1>
<p class="paragraph">
paragraph <span>span it</span>
<a href="">link it</a>
</p>
Using the following CSS rules gives us the output after:
:is(#header, p) span,
:is(#header, p) a {
color: red;
}
Now, let’s say we want to give the span
and the link text in the paragraph another color of blue
. We can do this by adding the following rule:
.paragraph span,
.paragraph a {
color: blue;
}
The earlier rule will override the blue
color despite being further down the line:
As a quick fix, we can enforce our blue
color by using the !important
notation like so:
:is(#header, p) span,
:is(#header, p) a {...}
.paragraph span,
.paragraph a {
color: blue !important;
}
But, as you may guess, that is bad practice, so we must not be quick to use the !important
notation. Instead, we can start by analyzing how every selector works. The :is()
is used in the code is a pseudo-class function for writing mega selectors in a more compressed form.
So, here is the following rule in the above code:
:is(#header, p) span,
:is(#header, p) a {
color: red;
}
Which is equivalent to the following:
#header span,
p span,
#header a,
p a {
color: red;
}
So, why is .paragraph span
and .paragraph a
not overriding the color despite having a specificity score of 0011
, which is higher than 0002
of the p span
and p a
.
Well, every selector in the :is()
uses the highest specificity in the list of arguments. In that case, both the #header
and the p
in the :is(#header, p)
uses the specificity score of the #header
, which is 0100
. Thus, the browser sticks to its value because it has a higher specificity.
Thus, anytime we see this type of conflict, we are better off not using the pseudo-class function and sticking to its equivalent like the following:
#header span,
p span,
#header a,
p a {
color: red;
}
Now, we should be able to see the expected result without using the !important
notation that disrupts cascade order.
You can see for yourself on CodeSandbox.
!important
declaration?Below are a few occasions where using the !important
notation is recommended.
Assuming we want to style all buttons on a page to look the same, we can write a CSS rule that can be reused across a page. Let’s take a look at the following markup and style below:
<p>Subscribe button : <a class="btn" href="#">Subscribe</a></p>
<section class="content">
<p>
This <a href="#" class="btn">button</a> style is affected by a higher
specificity value .
</p>
A link here: <a href="#">Dont click</a>
</section>
Followed by the CSS:
.btn {
display: inline-block;
background: #99f2f5;
padding: 8px 10px;
border: 1px solid #99f2f5;
border-radius: 4px;
color: black;
font-weight: normal;
text-decoration: none;
}
.content a {
color: blue;
font-weight: bold;
text-decoration: underline;
}
In the above code, we can see that the button link within the section
element is targeted by both selectors in the CSS. And, we learned that for conflicting rules, the browser will use the most specific rule. As we expect, .content a
has a score of 0011
while .btn
has a score of 0010
.
The page will look like this:
In this case, we can enforce the .btn
rule by adding the !important
notation to the conflicting declarations like this:
.btn {
/* ... */
color: black !important;
font-weight: normal !important;
text-decoration: none !important;
}
The page now looks as we expect:
See for yourself on CodeSandbox.
This mostly happens when we don’t have total control over the working code. Sometimes, when we work with a content management system like WordPress, we may find that an inline CSS style in our WordPress theme is overruling our custom style.
In this case, the !important
declaration is handy to override the theme inline style.
The !important
declaration is never meant to be used as we desire. We must only use it if absolutely necessary, such as a situation where we have less control over the code or very extreme cases in our own code.
Whether or not we use it depends on how we understand the core CSS mechanism, and in this tutorial, we covered that as well.
I hope you enjoyed reading this post. If you have questions or contributions, share your thought in the comment section and remember to share this tutorial around the web.
Source: https://blog.logrocket.com/understanding-css-important-declaration/
1641660425
CNRoom (Chats Noirs Room) is a header-only key-value database library using C++17 (std::filesystem
and std::variant
) and based on local files. It is actually in development by Fatih#6810 (accfldekur@gmail.com) from Moonlit Black Cats.
Installation
CNRoom is header-only, you just need a compiler that supports C++17 (std::filesystem
and std::variant
) then to include CNRoom/Room.hpp
after downloading files in the include directory. You may also need to link libstdc++fs
to your project in order to compile the std::filesystem
library that CNRoom uses.
Library vocabulary
I use the arrangement metaphor, you can imagine a room (base directory) with several drawers (file), inside these drawers you can tidy up papers (key) with informations written on them (values). CNRoom lets you assign several values of different types (std::string
, int
, double
, bool
) to a string called key and will write these values on a file of your choice (values are indexed in the order you write them). You can access to these values by the key.
Example code
A tutorial example code showing how easy CNRoom is to use!
//CNRoom
#include "CNRoom/Room.hpp"
//Standard
#include <iostream>
int main()
{
/// Stream class
////////////////////////////////////////////////////////////
CNRoom::Stream stream("database/lebgdu92.hkn", true); ///< Open a file, create new if doesn't exist
stream << CNRoom::Key{"mail", {"lebgdu92@gmail.com", true}}; ///< Write using <<
stream >> "mail"; ///< Read using >>
//Show method 1: std::get<Type>
std::cout << std::get<std::string>(stream()[0]) << std::endl; ///< Retreive key using () and value using []
stream.remove("mail"); ///< Remove a key
/// Room helper class
////////////////////////////////////////////////////////////
CNRoom::Room room;
room.connect("database", true); ///< Base directory (current path by default)
room.open("lebgdu92.hkn", [](auto& stream) ///< Open a file
{
stream.write({"sword", {"Sword of the Warrior", false, 4.85, 0}}); ///< Write using function write()
for(const auto& it: stream.read("sword").values) ///< Read using function read()
{
//Show method 2: Visit
std::visit([](auto const& value){ std::cout << value << ' '; }, it.standard());
}
}, true);
room.destroy("lebgdu92.hkn"); ///< Delete a file
/// Shortcut functions
////////////////////////////////////////////////////////////
room.quick_write("lebgdu92.hkn", {"sword", {"Sword of the Warrior", false, 4.85, 0}});
//Show method 3: Convert to string using Key::string()
std::cout << CNRoom::Key::string(room.quick_read("lebgdu92.hkn", "sword")[2]) << std::endl;
return 0;
}
Output:
lebgdu92@gmail.com
Sword of the Warrior 0 4.85 0 4.850000
Documentation
Struct and classes provided in CNRoom/Room.hpp
.
Class & members | Description |
---|---|
Variant | Class inheriting from std::variant and internally converting const char* to std::string if needed. |
Variant::standard() | Convert to standard std::variant . |
Struct & members | Description |
---|---|
Key | Struct that represents a key with a name and a vector of values. |
static Key::string(value) | Convert value to std::string. |
Key::name | Name of the key. |
Key::values | Vector of variant<string, int, double, bool>, access values with std::get, std::visit or Key::string. |
Key::operator[] | Access value by index. |
Class & members | Description |
---|---|
Stream | Stream class to operate on files. |
Stream::operator() | Returns a reference to the internal key. |
Stream::write(key) | Write a key. |
Stream::operator<< | Write a key. |
Stream::read(name) | Read a key by name. |
Stream::operator>> | Read a key by name. |
Stream::remove(name) | Remove a key. |
Some helper functions are provided in the Room class.
Class & members | Description |
---|---|
Room | Stream wrapper class. |
Room::connect(path) | Set the base directory. Optional, current path by default. |
Room::open(file, function) | Opens a file and call the given function. |
Room::exists(file) | Check if the given file exists. |
Room::destroy(file) | Delete a file. |
Room::quick_write(file, key) | Short way to write a key. |
Room::quick_read(file, name) | Short way to read a key. |
Performances
Can write and read keys of 5 values in a rate of 120 keys per second with my poor Toshiba DT01ACA100.
Download Details:
Author: swordfatih
Source Code: https://github.com/swordfatih/CNRoom
License: View license